Skip to main content
 首页 » 编程设计

python之我可以操纵 sorted() 的组织方式吗

2025年05月04日16yjmyzz

我正在处理大量数据(元组列表),我想对其进行组织。更具体地说:

# my characters for the items in the strings are 1-9,a-e 
# the results of my previous program produce a list of tuples 
# e.g. ('string', int), where int is the count of occurrence of that string in my data 
# my program currently lists them by count order, starting highest to lowest 
 
>>> print results #results from the previous part of my code 
[('7b7', 23522), ('dcd',23501)....('ccc',1)] 
 
>>> for three_grams in results: 
    print (sorted(three_grams)) 
 
[23522, '7b7'] 
[23501, 'dcd'] 
.... 
[1, 'ccc'] 

我不确定为什么它会切换 int 和 string... 但我想以相反的方式对它们进行排序。理想情况下,

[('111',803), ('112', 2843), ('113', 10)....('fff', 12)] 

有没有办法控制 sorted() 函数的排序方式?我可以改为在元组的字符串位中按 1-9a-e 排序吗?

(另外,我以前生成这些结果的程序不会打印零计数的结果,我想得到一些帮助。不确定我是否应该在这里发布它或在那里对我的整个代码提出另一个讨论问题?什么是 stackoverflow 礼节?我还是新手)

请您参考如下方法:

您正在对单个结果进行排序。

您需要对所有结果进行排序。

sorted 可以接受一个 key 参数。来自 the documentation :

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

我们将使用result[0]作为比较键,即'7b7'、'dcd'和 'ccc':

>>> results = [('7b7', 23522), ('dcd',23501), ('ccc',1)] 
 
>>> sorted(results, key=lambda result: result[0]) 
[('7b7', 23522), ('ccc', 1), ('dcd', 23501)] 

如果你不喜欢 lambda,你可以使用 itemgetter :

>>> from operators import itemgetter 
>>> sorted(results, key=itemgetter(0)) 
[('7b7', 23522), ('ccc', 1), ('dcd', 23501)]