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}]
>>>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM