zoukankan      html  css  js  c++  java
  • 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

     

  • 相关阅读:
    两种选择排序法
    三种方法求组合偶数字
    sizeof和mallo
    多态的概念与接口重用
    Delphi Exception的理解
    给老婆留着
    Delphi 一个简单的DELPHI自定义事件的例子
    Delphi 纯Pascal编写的程序,没有通过VCL
    Delphi 继承类的构造函数和析构函数的构建顺序
    Delphi 对象间数据的复制
  • 原文地址:https://www.cnblogs.com/xiaobingqianrui/p/8675056.html
Copyright © 2011-2022 走看看