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: def attrgetter(*items): if len(items) == 1: attr = items[0] def g(obj): return resolve_attr(obj, attr) else: def g(obj): return tuple(resolve_att(obj, attr) for attr in items) return g def resolve_attr(obj, attr): for name in attr.split("."): obj = getattr(obj, name) return obj
resolve_attr是用来处理属性名有.情 况; f = attrgetter('date.month') ,调用 f(b) 返回的是 b.date.month . 应用举例DSU: import operator def sort_by_attr(seq, attr): return sorted(seq, key=operator.attrgetter(attr)) def sort_by_attr_inplace(lst, attr): lst.sort(key=operator.attrgetter(attr)) 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:

def itemgetter(*items): if len(items) == 1: item = items[0] def g(obj): return obj[item] else: def g(obj): return tuple(obj[item] for item in items) return g

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'
from operator import itemgetter
def dict_items_sorted_by_value(d, reverse=False):
    return sorted(d.iteritems( ), key=itemgetter(1), reverse=reverse)

class Hist(object):
    def __init__(self,dict={}):
        self.adict = {}
    def add(self,item,increment = 1):
        self.adict[item] = increment + self.adict.get(item,0)
    def counts(self,reverse=False):
        return dict_items_sorted_by_value(self.adict,reverse)

if __name__ == '__main__':
    sentence = ''' Hello there this is a test.  Hello there this was a test,
           but now it is not. '''
    words = sentence.split( )
    c = Hist( )
    for word in words: c.add(word)
    print "Ascending count:"
    print c.counts( )
    print "Descending count:"
    print c.counts(reverse=True)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值