python lib 之 operator

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

operator. attrgetter ( attr [, args... ] )
这个函数返回一个可调用对象(Callable Objects),取此对象的attr属性值;如果参数是多个属性,则返回的是属性值tuple.
例如: f = attrgetter('name'), 则 f(b) 返回的是 b.namef = 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)
 

你可能感兴趣的:(Date,python,object,Module,import,tuples)