應用舉例:
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 "
AttributeError: 'tuple' object has no attribute 'sort'
>>> sorted(a)
[1, 2, 2, 3, 4]
)
>>> sorted (a)
[1, 3, 7, '1', 'a', 'n']>>> a
['1', 1, 'a', 3, 7, 'n']
> >> a.sort()
>>> a
[1, 3, 7, '1', 'a', 'n']
>>> 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
電話號碼依數字大小排序
>>> 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,'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],
... 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中文網!