Python中operator模块的操作
来源:互联网 发布:对冲基金编程 编辑:程序博客网 时间:2024/05/18 03:56
Operator模块提供了一系列与Python自带操作一样有效的函数。例如:operator.add(x, y)和表达式x+y是等效的。那些特殊类的方法都有自己的函数名;为了方便起见,一些函数名是没有前导和后置(__)。 在接下来讨论的函数涉及对象比较,逻辑运算,数学运算,队列操作和抽象类型测试。对象比较函数对所有对象都适用,并且都以他们所支持的丰富的比较操作而命名。operator模块是用c实现的,所以执行速度比python代码快。
逻辑操作
逻辑操作一般来说也可以应用在所有的,不同类型的值(value)上, 同时支持真值检验, 等式检验, 布尔操作:
from operator import *a = [1, 2, 3]b = aprint 'a =', aprint 'b =', bprintprint 'not_(a):', not_(a)print 'truth(a):', truth(a) #对象是否是真的print 'is_(a, b):', is_(a, b) # 检验对象是否相等print 'is_not(a, b) :', is_not(a, b)
运行结果:
a = [1, 2, 3]b = [1, 2, 3]not_(a): Falsetruth(a): Trueis_(a, b): Trueis_not(a, b) : False
比较操作
from operator import *a = 3b = 5for func in [lt, le, eq, ne, ge, gt]: print '{0}(a, b):'.format(func.__name__), func(a, b)
结果:
lt(a, b): True #等价于a<b le(a, b): True #等价于a<=beq(a, b): False #等价于a==b ne(a, b): True #等价于a!=bge(a, b): False #等价于a>=bgt(a, b): False #等价于a>b
其中’{0}(a, b):’.format(func.__name__
)得到的如上所示,也是一种很方便的写法
算术操作符
from operator import *a, b, c, d = -1, 2, -3, 4print 'a =', aprint 'b =', bprint 'c =', cprint 'd =', dprint '\nPositive/Negative:'print 'abs(a):', abs(a)print 'neg(a):', neg(a)print 'neg(b):', neg(b)print 'pos(a):', pos(a)print 'pos(b):', pos(b)
结果:
a = -1b = 2c = -3d = 4Positive/Negative:abs(a): 1neg(a): 1neg(b): -2pos(a): -1pos(b): 2
abs返回值得绝对值,neg返回(-obj), pos返回(+obj)。
a = -2b = 5.0print 'a =', aprint 'b =', bprint '\nArithmetic'print 'add(a, b) :', add(a, b)print 'div(a, b) :', div(a, b)print 'floordiv(a, b) :', floordiv(a, b)print 'mod(a, b) :', mod(a, b)print 'mul(a, b) :', mul(a, b)print 'pow(a, b) :', pow(a, b)print 'sub(a, b) :', sub(a, b)print 'truediv(a, b) :', truediv(a, b)
结果:
a = -2b = 5.0Arithmeticadd(a, b) : 3.0 # 返回 a+ bdiv(a, b) : -0.4 # 返回 a/ bfloordiv(a, b) : -1.0 # 返回 a// bmod(a, b) : 3.0mul(a, b) : -10.0pow(a, b) : -32.0sub(a, b) : -7.0truediv(a, b) : -0.4
mod表示取模, mul 表示相乘,pow是次方, sub表示相减
关于python运算符
a = 2b = 6print 'a =', aprint 'b =', bprint '\nBitwise:'print 'and_(a, b) :', and_(a, b)print 'invert(a) :', invert(a)print 'lshift(a, b) :', lshift(a, b)print 'or_(a, b) :', or_(a, b)print 'rshift(a, b) :', rshift(a, b)print 'xor(a, b) :', xor(a, b)
结果:
a = 2b = 6Bitwise:and_(a, b) : 2invert(a) : -3lshift(a, b) : 128or_(a, b) : 6rshift(a, b) : 0xor(a, b) : 4
其中:and 表示按位与, invert 表示取反操作, lshift表示左位移, or表示按位或, rshift表示右位移,xor表示按位异或。
原地操作符
即in-place操作, x += y 等同于 x = iadd(x, y), 如果复制给其他变量比如z = iadd(x, y)等同与z = x; z += y
print '\nIn-place operator'a = 3b = 4c = [1, 2]d = ['a', 'b']print 'a =', aprint 'b =', bprint 'c =', cprint 'd =', dprinta = iadd(a, b)print 'a = iadd(a, b) =>', aprintc = iconcat(c, d)print 'c = iconcat(c, d) =>', c
结果:
In-place operatora = 3b = 4c = [1, 2]d = ['a', 'b']a = iadd(a, b) => 7c = iconcat(c, d) => [1, 2, 'a', 'b']
属性和元素的获取方法
属性获取方法类似于 lambda x, n=’attrname’:getattr(x,n)
print 'The attributes and elements of the collection method'class MyObj(object): def __init__(self, arg): super(MyObj, self).__init__() self.arg = arg def __repr__(self): return 'MyObj(%s)' % self.arg# 列表推导式非常方便objs = [MyObj(i) for i in xrange(5)]print "Object:", objs#获取属性值 g = attrgetter("arg") # 属性获取vals = [g(i) for i in objs] #g(i)得到属性为arg的对象的属性值print "arg values:", valsobjs.reverse() # 列表反转print "reversed:", objsprint "sorted:", sorted(objs, key=g) # 排序,按key排序,在此为属性值排序,默认为升序
结果:
The attributes and elements of the collection methodObject: [MyObj(0), MyObj(1), MyObj(2), MyObj(3), MyObj(4)]arg values: [0, 1, 2, 3, 4]reversed: [MyObj(4), MyObj(3), MyObj(2), MyObj(1), MyObj(0)]sorted: [MyObj(0), MyObj(1), MyObj(2), MyObj(3), MyObj(4)]
元素获取方法类似于:lambda x,y=5:x[y],除了序列之外,元素获取方法还适用于映射
l = [dict(val=-1*i) for i in xrange(4)] # 得到字典“val”作为keyprint "dictionaries:", lg = itemgetter("val") # 元素获取vals = [g(i) for i in l]print "values: ", valsprint "sorted:", sorted(l, key=g) # 按照元素排序l = [(i,i*-2) for i in xrange(4)] # 得到元组print "tuples: ", lg = itemgetter(1) # 得到l的第一域的值,对比字典:是键对应的值vals = [g(i) for i in l]print "values:", valsprint "sorted:", sorted(l, key=g) # 按照元组第一域排序
结果:
dictionaries: [{'val': 0}, {'val': -1}, {'val': -2}, {'val': -3}]values: [0, -1, -2, -3]sorted: [{'val': -3}, {'val': -2}, {'val': -1}, {'val': 0}]tuples: [(0, 0), (1, -2), (2, -4), (3, -6)]values: [0, -2, -4, -6]sorted: [(3, -6), (2, -4), (1, -2), (0, 0)]
结合操作符和定制类
operator模块中的函数通过相应操作的标准Python接口完成工作,所以它们不仅适用于内置类型,还适用于用户自定义类型。
from operator import *class MyObj(object): def __init__(self, val): super(MyObj, self).__init__() self.val = val def __str__(self): return "MyObj(%s)" % self.val def __lt__(self, other): # 用户自定义lt的形式 return self.val < other.val def __add__(self, other): # 用户自定义add的输出形式 return MyObj(self.val + other.val)a = MyObj(1)b = MyObj(2)print lt(a, b)print add(a,b)
结果:
TrueMyObj(3) # 自定义的形式
类型检查
operator 模块还包含一些函数用来测试映射、数字和序列类型的API兼容性
class NoType(object): passclass MultiType(object): def __len__(self): return 0 def __getitem__(self, name): return "mapping" def __int__(self): return 0o = NoType()t = MultiType()for func in [isMappingType, isNumberType, isSequenceType]: print "%s(o):" % func.__name__, func(o) print "%s(t):" % func.__name__, func(t)
结果:
isMappingType(o): FalseisMappingType(t): TrueisNumberType(o): FalseisNumberType(t): TrueisSequenceType(o): FalseisSequenceType(t): True
获取对象方法
class Student(object): def __init__(self, name): self.name = name def getName(self): return self.namestu = Student("Jim")func = methodcaller('getName') # 使用methodcaller可以获取对象的方法。print func(stu) # 获取对象的方法
结果:
Jim
附加range和xrange的区别:
>>> range(5) # 生成的是一个数组[0, 1, 2, 3, 4]>>> range(1,5)[1, 2, 3, 4]>>> range(0,6,2)[0, 2, 4]>>> xrange(5)xrange(5)>>> list(xrange(5)) # 生成的是一个生成器[0, 1, 2, 3, 4]>>> for i in range(0, 5): print i01234>>> for i in xrange(0, 5): # 结果和range完全相同,但本质是不同的 print i01234>>> type(range(1,10)) # 类型不同<type 'list'>>>> type(xrange(1,10))<type 'xrange'>>>>
所以xrange做循环的性能比range好,尤其是返回很大的时候
参考:
http://www.jb51.net/article/87550.htm
- Python中operator模块的操作
- python的operator模块
- Python中使用operator模块实现对象的多级排序
- Python中使用operator模块实现对象的多级排序
- python 中的 operator模块
- python 中的 operator模块
- python-operator模块
- Python中Boolean operator的一些特点
- c++中operator 操作
- operator--Python内部操作符对应的函数
- python中对文件、文件夹的操作 os模块
- Python中time和datetime模块对时间的操作
- Python中操作mysql的pymysql模块详解
- Python中操作mysql的pymysql模块详解
- Python中操作mysql的pymysql模块详解
- Python中操作mysql的pymysql模块详解
- Python 基础—— operator 模块
- Python 运算符模块operator库
- .NET预防SQL注入的简易代码
- MQTT 服务器
- UVA-1482 Playing With Stones(SG函数打表找规律)
- linux tcp Linux的SOCKET编程详解
- 双向链表
- Python中operator模块的操作
- 顺序表应用6:有序顺序表查询
- 387. First Unique Character in a String
- javascrpt里的reverse 反转
- dwz table表格自动适应宽度
- 锁的内存语义
- springcloud(八):配置中心服务化和高可用
- C#之数据类型转换
- POJ 3070 Fibonacci (矩阵快速幂)