-
dict
排序from operator import itemgetter dicts = {"key1": "1", "key2": "2", "key3": "3"} sorted_dict = sorted(phone_book.items(), key=itemgetter(1)) print(dict(sorted_dict)) # [('key1', '1'), ('key2', '2'), ('key3', '3')]
-
多维
list
排序from operator import itemgetter lists = [["B", 3, "key1"], ["A", 2, "key2"], ["C", 1, "key3"]] sorted(lists, key=itemgetter(0, 1)) # [['A', 2, 'key2'], ['B', 3, 'key1'], ['C', 1, 'key3']]
-
包含字典的
list
排序from operator import itemgetter rows = [ {'name': 'Jones', 'uid': 1003}, {'name': 'Beazley', 'uid': 1002}, {'name': 'Cleese', 'uid': 1001}, {'name': 'Jones', 'uid': 1004} ] rows_by_uid = sorted(rows, key=itemgetter('uid')) print(rows_by_uid) # [{'uid': 1001, 'name': 'Cleese'}, {'uid': 1002, 'name': 'Beazley'}, {uid': 1003, 'name': 'Jones'}, {'uid': 1004, 'name': 'Jones'}]
-
包含列表的
dict
根据列表元素排序from operator import itemgetter dicts = { "zhang3": ["B", 3, "key1"], "wang2": ["A", 2, "key2"], "li4": ["C", 1, "key3"], "liu5": ["E", 1, "key6"], "zhao6": ["D", 5, "key5"] } sorted_dict = sorted(dicts.items(), key=lambda item: operator.itemgetter(1)(item[1])) print(dict(sorted_dict)) # {'li4': ['C', 1, 'key3'], 'liu5': ['E', 1, 'key6'], 'wang2': ['A', 2, 'key2'], 'zhang3': ['B', 3, 'key1'], 'zhao6': ['D', 5, 'key5']}
相关文章
- 11-04【Python】【Web.py】详细解读Python的web.py框架下的application.py模块
- 11-04python-已安装PySide但无法导入:“没有名为PySide的模块”
- 11-04python-PySide:分离一个spritesheet /分离图像成连续的颜色区域
- 11-04『Numpy学习指南』排序&索引&抽取函数介绍
- 11-04python-用PySide覆盖paintEvent的问题
- 11-04python-如何在基于事件的QTreeView中启用/禁用项目?
- 11-04python入门17 类和对象
- 11-04python中利用matplotlib绘图可视化知识归纳
- 11-04python-已成功安装PySide 2,但未成功安装Shiboken 2
- 11-04python-Scrapy爬网所有站点地图链接