關於python中的operator.itemgetter()函數的用法
阿新 • • 發佈:2018-03-23
int ems cnblogs get eve 對象 一個 div body
1. operator.itemgetter(num)函數
表示對對象的第num維數據進行操作獲取。
>>>import operator
>>>a = [1, 2, 3]
>>>b = operator.itemgetter(1)
>>>print(b)
返回是:
>>>operator.itemgetter(1)
也就是說,返回的並不是一個具體的數字,而是一個函數。
再進行如下操作:
>>>print(b(a))
返回:
2
即返回數組a的第二個元素。
2. 在使用sorted()函數進行排序時,也會使用到該函數。
sorted()函數語法:
sorted(iterable[, cmp[, key[, reverse]]])
使用方法如下:
>>>dict = {‘A‘:1, ‘B‘:2}
>>>dict_sort = sorted(dict.items(), key = operator.itemgetter(1), reverse = True)
>>>print(dict_sort)
返回:
>>>[(‘B‘,2),(‘A‘,1)]
即表示為對dict中第1維的元素進行降序排序。
關於python中的operator.itemgetter()函數的用法