Python - operator 模块 - 实现内部运算符的高级函数
目录
6-1 attrgetter(attr) 从操作数中获取attr,若请求多个属性,则返回元组
6-1-1 基于 attrgetter() + sorted() 实现对同类实例们的排序,基于属性值
6-2 itemgetter(item) 返回可调用对象,调用她的__getitem__()方法,若有多个则返回元组
6-2-1 itemgetter() + sorted 排序应用
6-2-2 itemgetter() + groupby() 根据特定字段分组迭代数据
6-3 methodcaller(name[, args...])
一、简单介绍及学习参考
该 operator 模块导出一组与Python的内部运算符相对应的高效函数。例如,
operator.add(x,y)等同于
x+y
。许多函数名称是用于特殊方法的函数名称,没有双下划线。为了向后兼容,其中许多都有一个带有双下划线的变体。为清楚起见,优选没有双下划线的变体。这些函数属于执行对象比较,逻辑运算,数学运算和序列运算的类别。
二、运算符的相关函数
请注意,这些函数可以返回任何值,这些值可能会或可能不会被解释为布尔值。
- a<b
operator.
lt
(a,b )operator.
__lt__
(a,b )- a<=b
operator.
le
(a,b )operator.
__le__
(a,b )- a == b
operator.
eq
(a,b )operator.
__eq__
(a,b )- a > b
operator.
ne
(a,b )operator.
__ne__
(a,b )- a >= b
operator.
ge
(a,b )operator.
__ge__
(a,b )- a != b
operator.
gt
(a,b )operator.
__gt__
(a,b )
三、逻辑运算符的相关函数
逻辑操作通常也适用于所有对象,并支持真值测试,身份测试和布尔操作
- 非运算
operator.
not_
(obj)operator.
__not__
(obj)- 如果obj为真,则返回True,否则返回False。这相当于使用bool构造函数。
operator.
truth
(obj)- 返回 a is b
operator.
is_
(a, b)- 返回 a is not b
operator.
is_not
(a, b)
四、四则运算和位运算
operator.
abs
(obj)operator.
__abs__
(obj)
- 返回obj的绝对值
operator.
add
(a, b)operator.
__add__
(a, b)
- a+b
operator.
and_
(a, b)operator.
__and__
(a, b)
- 返回与运算,a and b
operator.
floordiv
(a, b)operator.
__floordiv__
(a, b)
- a // b
operator.
index
(a)operator.
__index__
(a)
- a.__index__()
operator.
inv
(obj)operator.
invert
(obj)operator.
__inv__
(obj)operator.
__invert__
(obj)
- 返回数字obj的按位反转。这相当于
~obj
operator.
lshift
(a, b)operator.
__lshift__
(a, b)
- 返回一个左移b
operator.
mod
(a, b)operator.
__mod__
(a, b)
- 返回。
a % b
operator.
mul
(a, b)operator.
__mul__
(a, b)
- 返回,a和b数字。
a * b
operator.
matmul
(a, b)operator.
__matmul__
(a, b)
- 返回。
a @ b
- New in version 3.5.
operator.
neg
(obj)operator.
__neg__
(obj)
- 返回obj negated(
-obj
)。operator.
or_
(a, b)operator.
__or__
(a, b)
- 返回按位或a和b。
operator.
pos
(obj)operator.
__pos__
(obj)
- 返回obj positive(
+obj
)。operator.
pow
(a, b)operator.
__pow__
(a, b)
- Return
a ** b
, for a and b numbers.operator.
rshift
(a, b)operator.
__rshift__
(a, b)
- Return a shifted right by b.
operator.
sub
(a, b)operator.
__sub__
(a, b)
- Return
a - b
.operator.
truediv
(a, b)operator.
__truediv__
(a, b)
- Return
a / b
where 2/3 is .66 rather than 0. This is also known as “true” division.operator.
xor
(a, b)operator.
__xor__
(a, b)
- Return the bitwise exclusive or of a and b.
五、基于序列的操作
- 使用序列的操作(其中一些也带有映射):
operator.
concat
(a, b)operator.
__concat__
(a, b)
- Return
a + b
for a and b sequences.operator.
contains
(a, b)operator.
__contains__
(a, b)
- Return the outcome of the test
b in a
. Note the reversed operands.operator.
countOf
(a, b)
- Return the number of occurrences of b in a.
operator.
delitem
(a, b)operator.
__delitem__
(a, b)
- Remove the value of a at index b.
operator.
getitem
(a, b)operator.
__getitem__
(a, b)
- Return the value of a at index b.
operator.
indexOf
(a, b)
- Return the index of the first of occurrence of b in a.
operator.
setitem
(a, b, c)operator.
__setitem__
(a, b, c)
- Set the value of a at index b to c.
operator.
length_hint
(obj, default=0)
- Return an estimated length for the object o. First try to return its actual length, then an estimate using, object.__length_hint__() and finally return the default value.
六、通用属性和项目的查找工具
6-1 attrgetter(attr) 从操作数中获取attr,若请求多个属性,则返回元组
- After
f=attrgetter('name')
, the callf(b)
returnsb.name
.- After
f=attrgetter('name','date')
, the callf(b)
returns(b.name,b.date)
.- After
f=attrgetter('name.first','name.last')
, the callf(b)
returns(b.name.first,b.name.last)
.6-1-1 基于 attrgetter() + sorted() 实现对同类实例们的排序,基于属性值
from operator import attrgetter class User: def __init__(self, uid): self.uid = uid def __repr__(self): return 'User({})'.format(self.uid) # 实例列表 users = [User(1), User(23), User(14), User(0)] # sorted 基于key排序 sor_users = sorted(users, key=attrgetter('uid')) print(sor_users) # [User(0), User(1), User(14), User(23)] # 可以进行min 、max函数排序 min_users = min(users, key=attrgetter('uid')) print(min_users) # User(0) max_users = max(users, key=attrgetter('uid')) print(max_users) # User(23)
6-2 itemgetter(item) 返回可调用对象,调用她的__getitem__()方法,若有多个则返回元组
- After
f=itemgetter(2)
, the callf(r)
returnsr[2]
.- After
g=itemgetter(2,5,3)
, the callg(r)
returns(r[2],r[5],r[3])
.>>> itemgetter(1)('ABCDEFG') 'B' >>> itemgetter(1,3,5)('ABCDEFG') ('B', 'D', 'F') >>> itemgetter(slice(2,None))('ABCDEFG') 'CDEFG' >>> soldier = dict(rank='captain', name='dotterbart') >>> itemgetter('rank')(soldier) 'captain'
6-2-1 itemgetter() + sorted 排序应用
# 对元组列表,根据元组内值,进行排序 >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)] >>> getcount = itemgetter(1) >>> list(map(getcount, inventory)) [3, 2, 5, 1] >>> sorted(inventory, key=getcount) [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)] # 对字典列表,根据字典内值,进行排序 from operator import itemgetter rows = [ {'a': 'a', 'b': 'b', 'uid': 0}, {'a': 'a4', 'b': 'b1', 'uid': 4}, {'a': 'a2', 'b': 'b2', 'uid': 2}, {'a': 'a1', 'b': 'b3', 'uid': 1}, {'a': 'a3', 'b': 'b4', 'uid': 3}, ] rows_by_a = sorted(rows,key=itemgetter('a')) rows_by_uid = sorted(rows,key=itemgetter('uid')) print(rows_by_a) print(rows_by_uid) # [{'a': 'a', 'b': 'b', 'uid': 0}, {'a': 'a1', 'b': 'b3', 'uid': 1}, {'a': 'a2', 'b': 'b2', 'uid': 2}, {'a': 'a3', 'b': 'b4', 'uid': 3}, {'a': 'a4', 'b': 'b1', 'uid': 4}] # itemgetter接受多个关键词,前主后副依次递减 row = sorted(rows,key=itemgetter('uid','a','b')) # 同样适用于min max函数 row = min(rows,key=itemgetter('uid','a','b')) row = max(rows,key=itemgetter('uid','a','b'))
6-2-2 itemgetter() + groupby() 根据特定字段分组迭代数据
from operator import itemgetter from itertools import groupby rows = [ {'adress': '5412 N', 'date': '07/01/2018'}, {'adress': '542 N', 'date': '07/01/2018'}, {'adress': '1212 N', 'date': '07/12/2018'}, {'adress': '3212 N', 'date': '07/10/2018'}, {'adress': '12 N', 'date': '07/15/2018'}, ] for date, items in groupby(rows, key=itemgetter('date')): print(date) for i in items: print(' ', i) ''' 07/01/2018 {'adress': '5412 N', 'date': '07/01/2018'} {'adress': '542 N', 'date': '07/01/2018'} 07/12/2018 {'adress': '1212 N', 'date': '07/12/2018'} 07/10/2018 {'adress': '3212 N', 'date': '07/10/2018'} 07/15/2018 {'adress': '12 N', 'date': '07/15/2018'} '''
6-3
methodcaller
(name[, args...])
- After
f=methodcaller('name')
, the callf(b)
returnsb.name()
.- After
f=methodcaller('name','foo',bar=1)
, the callf(b)
returnsb.name('foo', bar=1)
.