是否有一种快速简便的方法来对包含两项的元组列表进行排序? (我要排序的元组的简短列表:
[('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:双重排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29292111/