如何通过两个项目对元组列表进行排序python

时间:2018-12-14 11:52:52

标签: sorting

mylist = [('Action',1) , ('Horror',2) , ('Adventure',0) , ('History',2) , ('Romance',1) ,('Comedy',1)]

我有一个这样的元组列表:

Action: 1
Horror: 2
Adventure: 0
History: 2
Romance: 1
Comedy: 1

我想按两个元素(名称(按字母顺序)和值)对它进行排序

我的结果应该是:

History: 2
Horror: 2
Action: 1
Comedy: 1
Romance: 1
Adventure: 0

2 个答案:

答案 0 :(得分:0)

以下方法应该起作用:

from operator import itemgetter

sorted_list = sorted(mylist, key=itemgetter(0,1), reverse=True)

您可以在本文档的“操作员模块功能”部分中了解有关此方法的更多信息: https://wiki.python.org/moin/HowTo/Sorting/

答案 1 :(得分:0)

from collections import defaultdict

mylist = [('Action',1) , ('Horror',2) , ('Adventure',0) , ('History',2) , ('Romance',1) ,('Comedy',1)]

category = defaultdict(list)

for item in mylist:
    category[item[1]].append(item[0])

sorted(category.items())
keylist = category.keys()
for key in sorted(keylist, reverse = True):
    valuelist = category[key]
    valuelist.sort()
    category[key] = valuelist
    for v in valuelist:
        print(str(v),str(key))

输出如下:

History 2
Horror 2
Action 1
Comedy 1
Romance 1
Adventure 0