Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Module operator trong Python: hàm thay thế toán tử

Module operator cung cấp hàm chức năng tương đương các toán tử, hữu ích cho functional programming (map, reduce, sorted key...).

1. Toán tử số học

HàmTương đươngVí dụ
add(a,b)a + badd(56,45)=101
sub(a,b)a - bsub(56,45)=11
mul(a,b)a * bmul(56,45)=2520
truediv(a,b)a / btruediv(56,45)=1.244
floordiv(a,b)a // bfloordiv(56,45)=1
mod(a,b)a % bmod(56,45)=11
pow(a,b)a ** bpow(5,3)=125

2. Toán tử quan hệ

3. Toán tử logic

from operator import truth, not_, is_, is_not
print(truth([1,2]))     # True
print(not_([1,2]))      # False
print(is_(a, b))        # a is b
print(is_not(a, b))     # a is not b

4. Toán tử bitwise

from operator import and_, or_, xor, invert, lshift, rshift
print(and_(5,3))   # 1
print(or_(5,3))    # 7
print(xor(5,3))    # 6
print(invert(5))   # -6
print(lshift(5,1)) # 10
print(rshift(5,1)) # 2

5. Truy cập item/attribute (rất hữu ích cho sorted key)

from operator import itemgetter, attrgetter, methodcaller

data = [{'name':'A','age':3}, {'name':'B','age':1}]
print(sorted(data, key=itemgetter('age')))  # [{'name':'B'...}, {'name':'A'...}]

class Person:
    def __init__(self, name, age): self.name, self.age = name, age
    def greet(self): return f"Hi {self.name}"

people = [Person('A',3), Person('B',1)]
print(sorted(people, key=attrgetter('age')))
print(list(map(methodcaller('greet'), people)))

6. Ví dụ thực tế: sort dict list đa tiêu chí

from operator import itemgetter
data = [{'name':'A','score':90}, {'name':'B','score':90}, {'name':'C','score':85}]
# score giảm, name tăng
print(sorted(data, key=itemgetter('score', 'name'), reverse=True))
# Cách khác: sorted(data, key=lambda x: (-x['score'], x['name']))
HàmTương đươngVí dụ
lt(a,b)a < blt(5,10)=True
le(a,b)a <= ble(10,10)=True
eq(a,b)a == beq(12,12)=True
gt(a,b)a > bgt(5,5)=False
ge(a,b)a >= bge(5,5)=True
ne(a,b)a != bne(15,12)=True