sorting - 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
解决方案
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
推荐阅读
- postgresql - docker-compose.yml,postgress,如何在 init.sql 文件中设置 db、tables 和 prepop?
- python - 单击按钮时运行python脚本
- python - Zapier 操作代码:Python 不会使用 input_data 变量运行
- javascript - 胜利堆栈中水平条的间距和大小?
- javascript - 使用 Jest 和 Enzyme,如何测试通过 props 传入的函数?
- javascript - 将 Python 字符串列表导入 Javascript 脚本(HTML 文件)
- python - 有没有更好的方法来覆盖 Marshmallow.fields.List?
- redirect - 登录站点 intead Admin/cmsadministration.aspx 后如何重定向到 kentico 的主页?
- javascript - JavaScript:以功能方式重新组织画布渲染
- java - 映射和数组列表,如果索引为 getEntry() 为 null,则添加“0”