Python——sorted
来源:互联网 发布:网络教育专科学历 编辑:程序博客网 时间:2024/05/19 00:09
1.对字典进行排序:
d = {0: [2, 3], 1: [5, 4], 2: [9, 6], 3: [4, 7], 4: [8, 1], 5: [7, 2]}
1.1按键排序
print sorted(d.items(), lambda x, y: cmp(x[1][0], y[1][0]))
结果:
[(0, [2, 3]), (3, [4, 7]), (1, [5, 4]), (5, [7, 2]), (4, [8, 1]), (2, [9, 6])]
1.2按值元素排序(此处的值是一个list的第1个元素)
print sorted(d.items(), lambda x, y: cmp(x[1][1], y[1][1]))
结果:
[(4, [8, 1]), (5, [7, 2]), (0, [2, 3]), (1, [5, 4]), (2, [9, 6]), (3, [4, 7])]
注意:此处排序后生成的是tuple而不是dict对象。
1.3将列表转换为字典
dd = sorted(d.items(), lambda x, y: cmp(x[1][0], y[1][0]))print dict(zip([x[0] for x in dd],[x[1] for x in dd]))
结果
{0: [2, 3], 1: [5, 4], 2: [9, 6], 3: [4, 7], 4: [8, 1], 5: [7, 2]}
0 0
- Python——sorted
- Python 基础——sorted
- python学习——sorted
- Python笔记——sorted
- python—sort()与sorted()函数
- Python学习(五)—sorted排序函数
- 廖雪峰的Python—sorted
- python———sort、sorted使用(对dict排序)
- Python学习——leetcode(Remove Duplicates from Sorted List)
- Python学习——leetcode(Merge Two Sorted Lists )
- Python高阶函数——map/reduce/filter/sorted
- Python学习(八)——map、reduce、filter、sorted
- Python函数式编程——sorted和sort函数
- LeetCode 88 — Merge Sorted Array(C++ Java Python)
- Python: sorted
- python sorted
- Python Sorted()
- Python--sorted
- 白话Spring(中级篇)---注解(2)
- 研究首屏时间?你先要知道这几点细节
- 素数筛选--总结
- DB2删除大表数据
- 格雷码的实现
- Python——sorted
- 在Linux下安装python package到指定目录
- Json概述以及python对json的相关操作
- 利用套接字进行网络编程
- Apache Kylin (v1.5.0) 发布,全新设计的新一代
- json----json----json--json---json
- 软件模式(简单工厂模式、工厂方法模式、抽象工厂模式)
- Java中千变万化字符串
- iOS9-URLScheme适配-引入白名单概念