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 บ้าง