`
djangofan
  • 浏览: 35831 次
社区版块
存档分类
最新评论

python lib 之 operator

 
阅读更多

operator module在使用内置函数如map,itertools.groupby,sorted排序使用DSU技巧时,经常用到;这里面最经常用到的两个函数是:

operator. attrgetter ( attr [ , args... ] )
这个函数返回一个可调用对象(Callable Objects),取此对象的attr属性值;如果参数是多个属性,则返回的是属性值tuple.
例如:f = attrgetter('name') ,则 f(b) 返回的是 b.name . f = attrgetter('name', 'date') ,则 f(b) 返回的是
(b.name, b.date) . Equivalent to:

resolve_attr是用来处理属性名有.情 况;f = attrgetter('date.month') ,调用 f(b) 返回的是 b.date.month .
应用举例DSU:
operator. itemgetter ( item [ , args... ] )

Return a callable object that fetches item from its operand using the operand’s __getitem__() method. If multiple items are specified, returns a tuple of lookup values. Equivalent to:

The items can be any type accepted by the operand’s __getitem__() method. Dictionaries accept any hashable value. Lists, tuples, and strings accept an index or a slice:

>>> 
itemgetter
(
1
)(
'ABCDEFG'
)

'B'

>>> 
itemgetter
(
1
,
3
,
5
)(
'ABCDEFG'
)

('B', 'D', 'F')

>>> 
itemgetter
(
slice
(
2
,
None
))(
'ABCDEFG'
)

'CDEFG'
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics