python排序sort()与sorted()
1.按照字母表输出一个序列
2.对记录的多个字段排序等
常用排序函数:
sort()
sorted()
比较:
1.sorted()应用范围更广
sorted(iterable[, cmp[, key[, reverse]]])
s.sorted([cmp[, key[, reverse]]])
示例:
>>> persons = [{'name':'Jon','age': 32}, {'name':'Alan','age': 50}, {'name': 'Bob', 'age':23}]
>>> sorted(persons, key=lambda x: (x['name'], -x['age']))
[{'age': 50, 'name': 'Alan'}, {'age': 23, 'name': 'Bob'}, {'age': 32, 'name': 'Jon'}]
sorted()可用于任意可迭代对象,sort()一般作用于列表
>>> a = (1,2,4,2,3)
>>> a.sort()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'sort'
>>> sorted(a)
[1, 2, 2, 3, 4]
2.sorted()返回排序后的列表,原列表不变,sort()直接修改原有列表。
sort()因为不需要复制原有列表,消耗内存少,效率高
>>> a=['1',1,'a',3,7,'n']
>>> sorted(a)
[1, 3, 7, '1', 'a', 'n']
>>> a
['1', 1, 'a', 3, 7, 'n']
>>> a.sort()
>>> a
[1, 3, 7, '1', 'a', 'n']
3.对于sort()和sorted()函数,传入参数key比参数cmp效率高。cmp传入的函数在整个排序过程中多次调用,开销大;key针对每个元素仅作一次处理。
>>> from timeit import Timer
>>> Timer(stmt="sorted(xs,key=lambda x:x[1])",setup="xs=range(100);xs=zip(xs,xs);").timeit(10000)
0.35391712188720703
>>> Timer(stmt="sorted(xs,cmp=lambda a,b: cmp(a[1],b[1]))",setup="xs=range(100);xs=zip(xs,xs);").timeit(10000)
0.4931659698486328
4.sorted()可以对多种数据结构排序
字典:
将phonebook的电话号按数字大小排序
>>> phonebook = {'Linda':'7750','Bob':'9345','Carol':'5834'}
>>> from operator import itemgetter
>>> sorted_pb = sorted(phonebook.iteritems(),key=itemgetter(1))
>>> sorted_pb
[('Carol', '5834'), ('Linda', '7750'), ('Bob', '9345')]
多维list:
对成绩、等级多字段排序
>>> from operator import itemgetter
>>> gameresult = [['Bob',95.00,'A'],['Alan',86.0,'C'],['Mandy',82.5,'A'],['Rob',86,'E']]
>>> sorted(gameresult, key=itemgetter(2, 1))
[['Mandy', 82.5, 'A'], ['Bob', 95.0, 'A'], ['Alan', 86.0, 'C'], ['Rob', 86, 'E']]
字典中混合list:
>>> mydict = {'Li':['M',7],
... 'Zhang': ['E',2],
... 'Wang':['p',3],
... 'Du':['C',2]}
>>> from operator import itemgetter
>>> sorted(mydict.iteritems(),key=lambda(k,v):operator.itemgetter(1)(v))
[('Zhang', ['E', 2]), ('Du', ['C', 2]), ('Wang', ['p', 3]), ('Li', ['M', 7])]
List中混合字典:
对多个key值rating和name排序
>>> gameresult = [{"name":"Bob","wins":10,"losses":3,"rating":75.00},
... {"name":"David","wins":3,"loses":5,"rating":57.00}]
>>> from operator import itemgetter
>>> sorted(gameresult,key=itemgetter("rating","name"))
[{'wins': 3, 'rating': 57.0, 'name': 'David', 'loses': 5}, {'wins': 10, 'losses': 3, 'name': 'Bob', 'rating': 75.0}]
>>>
更多python排序sort()与sorted() 相关文章请关注PHP中文网!
上一篇: 现在学python该学python2还是python3?
下一篇: JS怎么比较两个字符串