首頁  >  文章  >  後端開發  >  python排序sort()與sorted()

python排序sort()與sorted()

高洛峰
高洛峰原創
2017-02-13 17:29:581598瀏覽

應用舉例:

1.依照字母表輸出一個序列

2.對記錄的多個欄位排序等

常用排序函數:

sort()

sorted()

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 "", line 1, in
AttributeError: 'tuple' object has no attribute 'sort'
>>> sorted(a)
[1, 2, 2, 3, 4]

2. ,原列表不變,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 = {'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,'Aetter

>>> gameresult = [['Bob',95.00,'Aetter

>>> gameresult = [['Bob',95.00,'A'],5'A'] ,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],

... ang     'Zhang': ['E',2],

... ang    ['p',3],

...           'Du':['C',2]}
>>> from operator import itemgetter
>>> sorted(mydict.iteritems(),key=lambdaetter
>>> 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中文網!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn