Python中operator 模块的用法
operator 模块提供了一套与 Python 的内置运算符对应的高效率函数。1.函数的种类
函数包含的种类有:对象的比较运算、逻辑运算、数学运算和序列运算
2.比较运算
运算函数语法小于lt(a, b)a < b小于等于le(a, b)ab大于等于ge(a, b)a >= b等于eq(a, b)a == b不等于ne(a, b)a != b实例:
>>> from operator import *
>>> lt(1, 2)
True
>>> le(1, 3)
True
>>> le(3, 3)
True
>>> gt(10, 1)
True
>>> ge(10, 10)
True
>>> ge(10, 9)
True
>>> eq(10, 9)
False
>>> ne(10,10)
False
>>> ne(10, 9)
True3.逻辑运算
运算函数语法与and_(a, b)a & b或or_(a, b)a异或xor(a, b)a ^ b取反invert(a, b)~ a对象是否相等is_(a, b)a is b对象是否不相等is_not(a, b)a is not b真值truth(obj)obj实例:
>>> from operator import *
>>> and_(1, 1)
1
>>> or_(1, 2)
3
>>> xor(1, 2)
3
>>> invert(True)
-2
>>> invert(1)
-2
>>> invert(2)
-3
>>> a =
>>> b = 3
>>> is_(a, b)
False
>>> is_not(a, b)
True
>>> truth(a)
True4.数学运算
运算函数语法加add(a ,b)a + b除truediv(a, b)a / b乘mul(a, b)a * b减sub(a, b)a - b幂pow(a, b)a ** b负数neg(a)- a正数pos(a)+ a取模mod(a, b)a % b实例:
>>> from operator import *
>>> add(1, 2)
3
>>> truediv(3, 2)
1.5
>>> mul(3, 2)
6
>>> sub(3, 2)
1
>>> pow(2, 8)
256
>>> neg(5)
-5
>>> neg(-5)
5
>>> pos(10)
10
>>> pos(-10)
-10
>>> mod(10, 3)
15.序列运算
运算函数语法字符串拼接concat(seq1, seq2)seq1 + seq2包含contains(seq, obj)obj in seq索引赋值setitem(obj, i, v)obj = v索引删除delitem(obj, i)del obj索引取值getitem(obj, i)obj切片赋值setitem(seq, slice(i, j), values)seq = values切片删除delitem(seq, slice(i, j))del seq切片取值getitem(seq, slice(i, j))seq格式化mod(s, obj)s % obj实例:
>>> from operator import *
>>> concat('hello', ' Python')
'hello Python'
>>> a =
>>> contains(a, 2)
False
>>> setitem(a, 1, 5)
>>> a
>>> delitem(a, 2)
>>> a
>>> getitem(a, 1)
5
>>> setitem(a, slice(1, 3), 'ijk')
>>> a
>>> delitem(a, slice(2, 3))
>>> a
>>> mod('str %s', 'value')
'str value'6.attrgetter类
operator 模块的 attrgetter 类可以获取对象的属性用于 map(), stored() 操作
attrgetter实例:
from operator import *
class Student:
pass
def __init__(self, name, score):
self.name = name
self.score = score
def __repr__(self):
return '%s(name=%r,score=%r)' % (self.__class__.__name__, self.name, self.score)
if __name__ == '__main__':
students = [Student("zhangSan", 89),
Student("liSi", 60),
Student("wangWu", 70),
Student("xiaoMing", 100)]
#学习中遇到问题没人解答?小编创建了一个Python学习交流群:153708845
print("按照【分数】排序: ")
print(sorted(students, key=attrgetter('score'), reverse=True))
g = attrgetter("score") # 获取【分数】属性
vals =
print ('获取分数属性:' + vals)7.itemgetter类
operator 模块的 itemgetter 类会返回一个可调用对象,传入多个对象则返回元组
itemgetter实例:
>>> from operator import *
>>> itemgetter(3)('abcdefg')
'd'
>>> itemgetter(1, 3, 4)('abcdefg')
('b', 'd', 'e')
>>> itemgetter('name')({'name': 'liSi', 'age': 18})
'liSi'
>>> soldier = dict(rank='captain', name='dotterbart')
>>> itemgetter('rank')(soldier)
'captain'
>>> inventory = [('apple', 8), ('banana', 2), ('pear', 7)]
>>> getCount = itemgetter(1)
>>> list(map(getCount, inventory))
>>> sorted(inventory, key = getCount)
[('banana', 2), ('pear', 7), ('apple', 8)]
来源:https://www.cnblogs.com/djdjdj123/p/18141001
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页:
[1]