关于python中的operator.itemgetter()函数的用法

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维的元素进行降序排序。

原文地址:https://www.cnblogs.com/lliuye/p/8629579.html