Python:双重排序

是否有一种快速简便的方法来对包含两个项目的元组列表进行排序? (我要排序的元组的简短列表:

[('this', 4), ('in', 4), ('dedicated', 4), ('who', 3), ('us', 3), ('they', 3), ('so', 3), ('shall', 3), ('people', 3), ('is', 3), ('great', 3), ('dead', 3), ('are', 3), ('It', 3), ('which', 2), ('what', 2)]

我试图首先按频率(最大的第一个)排序它们,所以数字,然后按字母顺序排序.

这是我到目前为止:

word_list.sort(key=itemgetter(1,0), reverse = True)

这按频率按降序对列表进行排序.

最佳答案
我想我明白你想做什么.频率顺序不同于单词.为此你需要排序两次:

from operator import itemgetter

word_list = [('this', 4), ('in', 4), ('dedicated', 4), 
             ('who', 3), ('us', 3), ('they', 3), ('so', 3), ('shall', 3), ('people', 3), 
             ('is', 3), ('great', 3), ('dead', 3), ('are', 3), ('It', 3), 
             ('which', 2), ('what', 2)]


#first we set words in alphabetical order
word_list2 = sorted(word_list, key=lambda l: l[0].lower())

# then we sort them by frequency
word_list2 = sorted(word_list2, key=itemgetter(1), reverse = True)

print(word_list2)

结果是:

[('dedicated', 4), ('in', 4), ('this', 4), ('are', 3), ('dead', 3), ('great', 3), ('is', 3), ('It', 3), ('people', 3), ('shall', 3), ('so', 3), ('they', 3), ('us', 3), ('who', 3), ('what', 2), ('which', 2)]

这就是所谓的复杂排序.更多here.它的工作原理,因为python中的排序操作是稳定的.这意味着:

when multiple records have the same key, their original order is
preserved.

转载注明原文:Python:双重排序 - 代码日志