Python字典按值排序、包含字典的列表按字典值排序的方法
来源:互联网 发布:淘宝企业店名怎么改 编辑:程序博客网 时间:2024/06/05 16:21
- #-*- encoding=utf-8 -*-
- import operator
- #按字典值排序(默认为升序)
- x = {1:2, 3:4, 4:3, 2:1, 0:0}
- sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))
- print sorted_x
- #[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
- #如果要降序排序,可以指定reverse=True
- sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1), reverse=True)
- print sorted_x
- #[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]
- #或者直接使用list的reverse方法将sorted_x顺序反转
- #sorted_x.reverse()
- #取代方法是,用lambda表达式
- sorted_x = sorted(x.iteritems(), key=lambda x : x[1])
- print sorted_x
- #[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
- sorted_x = sorted(x.iteritems(), key=lambda x : x[1], reverse=True)
- print sorted_x
- #[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]
- #包含字典dict的列表list的排序方法与dict的排序类似,如下:
- x = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
- sorted_x = sorted(x, key=operator.itemgetter('name'))
- print sorted_x
- #[{'age': 10, 'name': 'Bart'}, {'age': 39, 'name': 'Homer'}]
- sorted_x = sorted(x, key=operator.itemgetter('name'), reverse=True)
- print sorted_x
- #[{'age': 39, 'name': 'Homer'}, {'age': 10, 'name': 'Bart'}]
- sorted_x = sorted(x, key=lambda x : x['name'])
- print sorted_x
- #[{'age': 10, 'name': 'Bart'}, {'age': 39, 'name': 'Homer'}]
- sorted_x = sorted(x, key=lambda x : x['name'], reverse=True)
- print sorted_x
- #[{'age': 39, 'name': 'Homer'}, {'age': 10, 'name': 'Bart'}]
- Python字典按值排序、包含字典的列表按字典值排序的方法
- Python字典按值排序、包含字典的列表按字典值排序的方法
- Python字典按值排序、包含字典的列表按字典值排序的方法
- Python字典按值排序、包含字典的列表按字典值排序的方法
- Python字典按值排序、包含字典的列表按字典值排序的方法
- Python字典按值排序、包含字典的列表按字典值排序的方法
- Python字典按值排序、包含字典的列表按字典值排序的方法
- Python字典按值排序、包含字典的列表按字典值排序的方法
- python 字典按值排序
- Python的字典排序
- Python 字典的排序
- python 字典的排序
- Python字典、列表排序
- python -- 有序字典, 有序字典的排序
- python 按照字典的值进行排序
- python 字典(dict)按值排序
- Python - 字典按值(value)排序
- Python中最快的字典排序方法
- 表单设计工具和报表工具
- IE设置对QTP和LR的影响
- 根据表名查询相关约束
- SSH 的详细使用方法
- 优先队列之二叉堆与d-堆
- Python字典按值排序、包含字典的列表按字典值排序的方法
- 有关google weahter api
- Gson的使用
- 大数据时代的历史机遇——产业变革与数据科学
- jquery实现简单瀑布流代码
- android的inputType值
- 一个IP每天只弹一次广告窗口
- IDC:协处理器显著增长 HPC广泛应用于大数据分析
- windows下的android开发环境搭建(基于Eclipse)