python函数之sorted与sort
Python list内置sort()方法用来排序,也可以用python内置的全局sorted()方法来对可迭代的序列排序生成新的序列。
sorted(iterable,key=None,reverse=False),返回新的列表,对所有可迭代的对象均有效
sort(key=None,reverse=False) 就地改变列表 reverse:True反序;False 正序
实例:
>>>sorted([1,5,3,2,9])
[1,2,3,5,9]
>>>a=[5,3,2,1,4]
>>>a.sort()
>>>a
[1,2,3,4,5] #若用list.sort()则list本身将被修改
>>>sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
[1,2,3,4,5] #sorted()对所有的可迭代序列都有效
在python2.4开始,list.sort()和sorted()增加key参数来指定一个函数,此函数在每个元素比较前被调用。
>>>sorted("This is a test string from Andrew".split(), key=str.lower) #加了key,忽略大小写
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This'] #key=len按照长度进行排序
>>>sorted("This is a test string from Andrew".split()) #未加key,默认大写在前,小写在后
['Andrew', 'This', 'a', 'from', 'is', 'string', 'test']
更多的情况是用复杂对象的某些值来对复杂对象进行排序。
>>> student_tuples = [('john', 'A', 15),('jane', 'B', 12),('dave', 'B', 10),]
>>> sorted(student_tuples, key=lambda student: student[2]) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
>>>student_tuples.sort(key=lambda x: x[2])
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
>>>s=”Hello79351WorldMyNameIsMrFiona0352231964”
>>>''.join(sorted(s,key=lambda x: (x.isdigit(),x.isdigit() and int(x)%2==0,x.islower(),x.isupper(),x)))
'FHIMMNWaadeeilllmnooorrsy113335579902246'
大写在前,小写在后,数字放在最后并且奇数在偶数之前
>>>s={‘a’:10,’t’:5,’c’:2,’b’:12}
>>>sorted(s,key=lambda x:x[0])
[‘a’,’b’,’c’,’t’]
>>>s=[]
- Python sort sorted函数详解
- python的排序函数sort,sorted
- python的排序函数sort,sorted在列表排序和字典排序中的应用详解和举例
- python3 sort sorted 函数应用
- Python的排序函数Sort,Sorted
- python中sort()、sorted()函数比较
- Python中的排序函数argsort,sort,sorted用法
- python中排序,函数sort、sorted、argsort,collections.OrderedDict类
- python—sort()与sorted()函数
- python中List的sort方法(或者sorted内建函数)的用法
- python中List的sort方法(或者sorted内建函数)的用法
- python中List的sort方法(或者sorted内建函数)的用法
- python3 sort sorted 函数应用
- Python中的排序函数argsort,sort,sorted
- 【转】python中List的sort方法(或者sorted内建函数)的用法
- Python sort sorted函数详解
- [python学习] 语言基础—排序函数(sort()、sorted()、argsort()函数)
- python中List的sort方法(或者sorted内建函数)的用法
- python3 sort sorted 函数应用
- [Python]sorted()函数与list.sort()函数