Python之operator库

operator库常用方法

Function Syntax
add(a+b) a + b
concat(seq1,seq2) seq1 + seq2
contains(seq, obj) obj in seq
div(a,b)(without future.division) a/b
truediv(a,b)(with future.division) a/b
floordiv(a,b) a // b
and_(a,b) a & b
xor(a, b) a ^ b
invert(a) ~a
or_(a, b) a b
pow(a,b) a ** b
is_(a,b) a is b
is_not(a,b) a is not b
setitem(obj, k, v) obj[k] = val
delitem(obj, k) del obj[k]
getitem(obj, k) obj[k]
lshift(a,b) a << b
mod(a,b) a % b
mul(a,b) a * b
neg(a) -a
not_(a) not a
pos(a) + a
rshift(a, b) a >> b
repeat(seq,i) seq * i
setitem(seq, slice(i,j),values) seq[i,j] =values
delitem(seq,slice(i,j),values) del seq[i,j]
getitem(seq, slice(i,j)) seq[i:j]
mod(s, obj) s % obj
sub(a, b) a-b
truth(obj) obj

operator.itemgetter

  返回一个可调用对象,获取项目使用的操作数的__getitem__()方法操作数。如果指定了多个项,则返回一个查找值元组。

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

>>> itemgetter(1)('ABCDEFG')
'B'
>>> itemgetter(1,3,5)('ABCDEFG')
('B', 'D', 'F')
>>> itemgetter(slice(2,None))('ABCDEFG')
'CDEFG'

operator.attrgetter

  返回一个可调用对象,通过其操作数获取属性。如果请求多个属性,则返回一个属性元组。属性名称也可以包含点。

def attrgetter(*items):
    if any(not isinstance(item, str) for item in items):
        raise TypeError('attribute name must be a string')
    if len(items) == 1:
        attr = items[0]
        def g(obj):
            return resolve_attr(obj, attr)
    else:
        def g(obj):
            return tuple(resolve_attr(obj, attr) for attr in items)
    return g

def resolve_attr(obj, attr):
    for name in attr.split("."):
        obj = getattr(obj, name)
    return obj

 

 

posted @ 2018-03-30 11:34  Fate0729  阅读(1364)  评论(0编辑  收藏  举报