python operator的itemgetter函数

先看下help帮助信息,

class itemgetter(__builtin__.object)
 |  itemgetter(item, ...) --> itemgetter object
 |  
 |  Return a callable object that fetches the given item(s) from its operand.
 |  After f = itemgetter(2), the call f(r) returns r[2].
 |  After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])

由此我们知道以下两点:

1、itemgetter函数用于返回操作对象的某个元素,具体取决于用户给的参数,对应到矩阵上,那就是返回某一维的元素

2、itemgetter函数并不是直接获取操作对象的值,而是定义了一个函数,通过该函数才能获取操作对象的值

看例子,

>>> a=[1,2,3]
>>> b(a)
2
>>> a=[1,2,3]
>>> b=operator.itemgetter(1)
>>> b(a)
2
>>> c=operator.itemgetter(1,2)
>>> c(a)
(2, 3)
>>> 

再看矩阵上,

>>> a=array([[1,2,3],[4,5,6],[7,8,9]])
>>> a
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> b=operator.itemgetter(1)
>>> c=operator.itemgetter(1,2)
>>> b(a)
array([4, 5, 6])
>>> c(a)
(array([4, 5, 6]), array([7, 8, 9]))
>>> 

不过大多数时候该函数用于获取多元组某个域的值,作为排序关键字,

>>> a=('Kobe', 24)
>>> b=operator.itemgetter(0)
>>> c=operator.itemgetter(1)
>>> b(a)
'Kobe'
>>> c(a)
24
>>> 

版权声明:本文为u010039418原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。