2014年1月20日 星期一

Python sort dic by keys, values. sort list

Python dict sort keys, values

>>>numbers = {'first': 1, 'second': 2, 'third': 3, 'Fourth': 4}
>>> [key for key in sorted(numbers.keys())]
['Fourth', 'first', 'second', 'third']
>>> [value for value  in sorted(numbers.values())]
[1, 2, 3, 4]

#################################################

sort by key:
>>> dic={'hello': 1, 'aa': 2,'b':3}
>>> sorted(dic.items())
[('aa', 2), ('b', 3), ('hello', 1)]
------
>>> sorted(dic.items(),key=itemgetter(0))


sort by values:
>>> dic={'hello': 1, 'aa': 2,'b':3}
>>> sorted( dic.items(), key= lambda x:x[1] )    #dic.items()取出了x=[key,value],sort 是用x[1]
[('hello', 1), ('aa', 2), ('b', 3)]
>>> sorted(dic.items(),key=lambda x:x[1],reverse=True)
[('b', 3), ('aa', 2), ('hello', 1)]
------
>>> sorted(dic.items(),key=itemgetter(1))

##################################################

>>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10),]

用 operator 函数来加快速度, 上面排序等价于:(itemgetter的用法)
>>> from operator import itemgetter, attrgetter
>>> sorted(students, key=itemgetter(2))

用 operator 函数进行多级排序
>>> sorted(students, key=itemgetter(1,2))  # sort by grade then by age
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

ref. http://www.pythoncentral.io/how-to-sort-python-dictionaries-by-key-or-value/
ref. http://obroll.com/how-to-sort-dictionary-by-keys-or-by-values-in-python/
ref. http://gaopenghigh.iteye.com/blog/1483864

沒有留言:

張貼留言