首页 > 解决方案 > python - 如何按两个项目对元组列表进行排序

问题描述

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

标签: sorting

解决方案


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

推荐阅读