2012/05/29

Python 串列(List)、字典(Dict) 的排序

List
直接對list本身排序
>>> l = [3, 2, 5, 4, 1]
>>> l.sort()
>>> l
[1, 2, 3, 4, 5]
>>> l.sort(reverse=True)
>>> l
[5, 4, 3, 2, 1]

不動到原始順序
>>> l = [3, 5, 4]
>>> sorted(l)
[3, 4, 5]
>>> l
[3, 5, 4]
根據element的運算結果
>>> l = ["tom", "Michael", "jenny"]
>>> l.sort(key=str.lower)
>>> l
['jenny', 'Michael', 'tom']


Dictionary
Dict本身是無序的,所以只能在輸出時做排序
>>> d = {"b": 1, "a": 3, "c": 2}
>>> d
{'a': 3, 'c': 2, 'b': 1}
>>> sorted(d)
['a', 'b', 'c']
>>> for key in sorted(d):
...     "%s: %d" % (key, d[key])
... 
'a: 3'
'b: 1'
'c: 2'


Dict in List
List.sort() 內的 key 是排序的依據,可以是 element 的屬性或是 function 運算後的結果
By function
>>> l = [{"id": 3, "name": "john"}, {"id": 2, "name": "brandon"}, {"id": 1, "name": "susan"}]
>>> l
[{'id': 3, 'name': 'john'}, {'id': 2, 'name': 'brandon'}, {'id': 1, 'name': 'susan'}]
>>> def my_func(d):
...     return d['id']
... 
>>> l.sort(key=my_func) 
>>> l
[{'id': 1, 'name': 'susan'}, {'id': 2, 'name': 'brandon'}, {'id': 3, 'name': 'john'}]

簡寫,use in-line function
>>> l.sort(key=lambda d:d['id'])   
>>> l
[{'id': 1, 'name': 'susan'}, {'id': 2, 'name': 'brandon'}, {'id': 3, 'name': 'john'}]
>>> l.sort(key=lambda d:d['name'])
>>> l
[{'id': 2, 'name': 'brandon'}, {'id': 3, 'name': 'john'}, {'id': 1, 'name': 'susan'}]


參考資料
HowTo/Sorting - PythonInfo Wiki



1 則留言:

  1. Statistics show tҺɑt aƅout a third of the US youth аre either overweight or obese.
    High triglycerides increаse the risk of ɑtherosclerosis development ɑnd it is advisable to keep in the range below 1.
    Make decisions about exercise and stгess-relieving aсtivities.


    Here is my web blog; revertir la diabetes de sergio russo pdf gratis

    回覆刪除