python之sorted
来源:互联网 发布:高考物理知乎 编辑:程序博客网 时间:2024/06/10 02:46
Sorted函数对列表进行排序,多数据多可以抽象为列表,所以其用途广泛。
函数原型::sorted(data, key=None, reverse=False)
Data是要排序的List对象,key是关键字,reverse是true的时候从大到小排序,默认是从小到大。
Key用来指定排序依据的关键字,单条件时指定一个,多条件依据优先次序指定多个关键字。指定方法是:若元素是tuple或者list,直接利用下标指定即可;若元素是字典,则需要利用字典key的名字指定关键字。
下面依次举例,指定关键字时候,均利用了两种方法。一是用了itemgetter函数,一个是利用lambda得到匿名函数。
1.元素是原子数据:
dataList = [4, 3, 9, 7, 10, 88, -5]print sorted(dataList,reverse = True)
2.元素是tuple,利用下标指定关键字
单条件排序
dataList = [(4, 6), (3, 92), (9, 10), (9, 17), (10, 54), (88, 3), (-5, 0)]print sorted(dataList, key = itemgetter(0), reverse = True)print sorted(dataList, key = lambda x : (x[0]), reverse = True)##result:[(88, 3), (10, 54), (9, 10), (9, 17), (4, 6), (3, 92), (-5, 0)][(88, 3), (10, 54), (9, 10), (9, 17), (4, 6), (3, 92), (-5, 0)]#use another key print sorted(dataList, key = itemgetter(1), reverse = True)print sorted(dataList, key = lambda x : (x[1]), reverse = True)##result:[(3, 92), (10, 54), (9, 17), (9, 10), (4, 6), (88, 3), (-5, 0)][(3, 92), (10, 54), (9, 17), (9, 10), (4, 6), (88, 3), (-5, 0)]
多条件排序,依次指定关键字即可,指定方法是利用下标
print sorted(dataList, key = itemgetter(0,1), reverse = True)print sorted(dataList, key = lambda x : (x[0], x[1]), reverse = True)#result:[(88, 3), (10, 54), (9, 17), (9, 10), (4, 6), (3, 92), (-5, 0)][(88, 3), (10, 54), (9, 17), (9, 10), (4, 6), (3, 92), (-5, 0)]
其中第一个单条件排序和多条件排序的 (9,10) 和 (9,17)位置不同,说明指定的关键字起到了效果。
3.元素是字典:
利用网上的一个数据
teamitems = [{'team':'France' , 'P':1 , 'GD':-3 , 'GS':1 , 'GA':4}, {'team':'Uruguay', 'P':7 , 'GD':4 , 'GS':4 , 'GA':0}, {'team':'SouthAfrica', 'P':4 , 'GD':-2 , 'GS':3 , 'GA':5}, {'team':'Mexico' , 'P':4 , 'GD':1 , 'GS':3 , 'GA':2}] sorted(teamitems, key = itemgetter('P', 'GD', 'GS', 'GA'), reverse = True)sorted(teamitems, key = lambda x : (x['P'], x['GD'], x['GS'], x['GA']), reverse = True)#result:{'P': 7, 'GD': 4, 'GS': 4, 'GA': 0, 'team': 'Uruguay'}{'P': 4, 'GD': 1, 'GS': 3, 'GA': 2, 'team': 'Mexico'}{'P': 4, 'GD': -2, 'GS': 3, 'GA': 5, 'team': 'SouthAfrica'}{'P': 1, 'GD': -3, 'GS': 1, 'GA': 4, 'team': 'France'}
0 0
- python之sorted
- python排序之sorted
- python之sort(),sorted()
- Python之 sort和sorted
- Python 高级特性之 sorted( )
- 学习廖雪峰python之sorted()
- python基础之map/reduce/filter/sorted
- Python: sorted
- python sorted
- Python Sorted()
- Python--sorted
- Python-----sorted
- python sorted
- python sorted
- python sorted
- python sorted
- Python sorted()
- python sorted
- vmware 安装,序列号
- 【Cocos2d-x3.0学习笔记 08】精灵来了
- Cstyle的UEFI导读:第18.0篇 NVRAM的工作原理(上)
- http://support.apple.com/kb/HT5559?viewlocale=en_US
- IOS征途之c语言-C语言中的scanf函数
- python之sorted
- scintilla例子程序makefile_vc 文件的分析
- How To Fix “Problem with MergeList /var/lib/apt/lists” Error In Ubuntu 11.04
- CI框架源码阅读笔记3 全局函数Common.php
- Codeforces 282E Sausage Maximization(字典树)
- rake db:create error
- eclipse 安装 swt 插件
- Intel XEON L/E/X/W 系列的区别
- 面试题 1