2018-01-03@望京
排序,立即想到用Python的內置函數sorted()
Python 2.x 中
sorted(...)
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
Python 3.x 中
sorted(iterable, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customise the sort order, and the
reverse flag can be set to request the result in descending order.
字典按key排序
>>> dic = {'a':9, 'c':3, 'f':12, 'b':1, 'd':7}
>>>
>>> sorted(dic)
['a', 'b', 'c', 'd', 'f']
>>>
>>> sorted(dic.keys())
['a', 'b', 'c', 'd', 'f']
>>>
>>> sorted(dic.values())
[1, 3, 7, 9, 12]
>>>
>>> sorted(dic.items())
[('a', 9), ('b', 1), ('c', 3), ('d', 7), ('f', 12)]
>>>
>>> for k in sorted(dic):
... print dic[k]
...
9
1
3
7
12
>>>
字典是無序的,對字典排序本身是一個沒有太大意義的事,但是面試的時候總會遇到==''
那么問題來了,如何對字典按照value排序呢(默認是對key進行排序)?
首先需要知道sorted()這個函數的幾個參數的意思(按照Python 3.x來說明):
- iterable? ?指的是可迭代對象,可以是dic,dic.items(), dic.keys(),? dic.values() 等等;
- key? ? ? ? ?key對應一個函數,用來選取參與比較的元素;
-?reverse? ?排序規則. reverse = True 或者 reverse = False(默認值);
Py2中使用sort的cmp參數自定義排序方式
>>>
>>> res = [{'name':'hi','age':10},{'name':None,'age':10},{'name':'bo','age':10},{'name':'aaa','age':10}]
>>>
>>> res.sort(cmp=lambda x, y: cmp(x['name'], y['name']))
>>>
>>> res
[{'age': 10, 'name': None}, {'age': 10, 'name': 'aaa'}, {'age': 10, 'name': 'bo'}, {'age': 10, 'name': 'hi'}]
>>>
使用key參數來實現
items()方法將字典的元素 轉化為了元組
>>> dic
{'a': 9, 'c': 3, 'b': 1, 'd': 7, 'f': 12}
>>> dic.items()
[('a', 9), ('c', 3), ('b', 1), ('d', 7), ('f', 12)]
>>>
>>> sorted(dic.items())
[('a', 9), ('b', 1), ('c', 3), ('d', 7), ('f', 12)]
>>>
>>> sorted(dic.items(), key=lambda x:x[1])
[('b', 1), ('c', 3), ('d', 7), ('a', 9), ('f', 12)]
>>>
使用zip來實現
>>> dic
{'a': 9, 'c': 3, 'b': 1, 'd': 7, 'f': 12}
>>>
>>> new_dic = zip(dic.values(), dic.keys())
>>>
>>> new_dic
[(9, 'a'), (3, 'c'), (1, 'b'), (7, 'd'), (12, 'f')]
>>>
>>> sorted(new_dic)
[(1, 'b'), (3, 'c'), (7, 'd'), (9, 'a'), (12, 'f')]
>>>