Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Operator Functions ใน Python (โมดูล operator)

Python มีฟังก์ชันในโมดูล operator สำหรับการดำเนินการทางคณิตศาสตร์ ตรรกะ สัมพันธ์ บิตเวส เป็นต้น ใช้แทน operators ปกติได้ และมีประโยชน์เมื่อต้องส่งฟังก์ชันเป็นอาร์กิวเมนต์ (higher-order functions)

การนำเข้า

import operator

1. Arithmetic Operations (เลขคณิต)

ฟังก์ชันเทียบเท่าคำอธิบาย
add(x, y)x + yบวก
sub(x, y)x - yลบ
mul(x, y)x * yคูณ
truediv(x, y)x / yหาร (คืน float)
floordiv(x, y)x // yหารปัดลง (คืน int)
mod(x, y)x % yโมดูล로 (เศษ)
pow(x, y)x ** yยกกำลัง

ตัวอย่าง


import operator
print('Add:', operator.add(56, 45))           # 101
print('Subtract:', operator.sub(56, 45))      # 11
print('Multiply:', operator.mul(56, 45))      # 2520
print('True div:', operator.truediv(56, 45))  # 1.244...
print('Floor div:', operator.floordiv(56, 45))# 1
print('Mod:', operator.mod(56, 45))           # 11
print('Pow:', operator.pow(5, 3))             # 125

2. Relational Operations (สัมพันธ์)

ฟังก์ชันเทียบเท่าคำอธิบาย
lt(x, y)x < yน้อยกว่า
le(x, y)x <= yน้อยกว่าหรือเท่ากับ
eq(x, y)x == yเท่ากับ
gt(x, y)x > yมากกว่า
ge(x, y)x >= yมากกว่าหรือเท่ากับ
ne(x, y)x != yไม่เท่ากับ

ตัวอย่าง


import operator
print('Less than:', operator.lt(5, 10))       # True
print('Less equal:', operator.le(10, 10))     # True
print('Greater:', operator.gt(5, 5))          # False
print('Greater equal:', operator.ge(5, 5))    # True
print('Equal:', operator.eq(12, 12))          # True
print('Not equal:', operator.ne(15, 12))      # True

3. Logical Operations (ตรรกะ)


print('not_(True):', operator.not_(True))     # False
print('truth([1,2]):', operator.truth([1,2])) # True (non-empty)
print('is_(a, b):', operator.is_(a, b))       # identity (a is b)
print('is_not(a, b):', operator.is_not(a, b)) # a is not b

4. Bitwise Operations (บิตเวส)

ฟังก์ชันเทียบเท่า
and_(x, y)x & y
or_(x, y)x | y
xor(x, y)x ^ y
invert(x)~x
lshift(x, y)x << y
rshift(x, y)x >> y

5. Container Operations (คอนเทนเนอร์)

ฟังก์ชันเทียบเท่าคำอธิบาย
contains(a, b)b in aตรวจสอบ membership
getitem(a, i)a[i]เข้าถึง item
setitem(a, i, v)a[i] = vกำหนดค่า item
delitem(a, i)del a[i]ลบ item
concat(a, b)a + bต่อ sequence
length_hint(obj)-ประมาณความยาว

ประโยชน์จริง: ใช้กับ higher-order functions


from operator import add, mul
from functools import reduce

numbers = [1, 2, 3, 4, 5]
print(reduce(add, numbers))   # 15 (sum)
print(reduce(mul, numbers))   # 120 (product)

# เรียงลำดับ list of tuples โดย element ที่ 2
data = [('a', 3), ('b', 1), ('c', 2)]
from operator import itemgetter
print(sorted(data, key=itemgetter(1)))  # [('b', 1), ('c', 2), ('a', 3)]

# itemgetter เร็วกว่า lambda
print(sorted(data, key=lambda x: x[1])) # ผลลัพธ์เดียวกัน

สรุป: โมดูล operator ให้ functional equivalents ของ operators ทำให้เขียน functional code ได้สะดวกและเร็วกว่า lambda บ้าง