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=[]