我正在处理大量数据(元组列表),我想组织这些数据.更具体:
# 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和字符串...但我想以相反的方式对它们进行排序.理想的情况下,
[('111',803), ('112', 2843), ('113', 10)....('fff', 12)]
有没有办法操纵sorted()函数的排序方式?我可以1-9a-e在元组的字符串位中进行排序吗?
(另外,我以前用于生成这些结果的程序不打印没有计数的结果,我想对此有所帮助.不确定我是否应该在此发布或在我的整个代码中再提出一个讨论问题?什么是stackoverflow礼仪?我还是新手)
您正在对单个结果进行排序.
您需要对所有结果进行排序.
sorted可以采取key参数.从文档:
key指定一个参数的函数,用于从每个列表元素中提取比较键:key=str.lower.默认值为None(直接比较元素).
我们将使用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)]
| 归档时间: | 
 | 
| 查看次数: | 59 次 | 
| 最近记录: |