是否有一种快速简便的方法来对包含两个项目的元组列表进行排序? (我想要排序的元组的简短列表:
[('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)
按频率按降序对列表进行排序。
答案 0 :(得分:3)
我想我明白你想做什么。频率顺序不同于单词。为此你需要排序两次:
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中的排序操作是稳定的。这意味着:
当多个记录具有相同的密钥时,其原始顺序为 保留。
答案 1 :(得分:1)
我会使用两个排序功能。一个就像你已经分类一样。然后按字母顺序对结果进行排序。这对你有意义吗?
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)]
word_list.sort(key=lambda i:i[1], reverse = True)
word_list.sort(key=lambda i:i[0].lower())