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

Trừ hai tuple trong Python

Khi cần trừ phần tử tương ứng của hai tuple (element-wise subtraction), có thể dùng map() với lambda hoặc zip() với comprehension.

Ví dụ

tuple_1 = (7, 8, 11, 0, 3, 4)
tuple_2 = (3, 2, 22, 45, 12, 9)

print(f"Tuple 1: {tuple_1}")
print(f"Tuple 2: {tuple_2}")

# Cách 1: map + lambda
result1 = tuple(map(lambda a, b: a - b, tuple_1, tuple_2))
print(f"\nCách 1 - map+lambda: {result1}")

# Cách 2: zip + generator expression (khuyến nghị)
result2 = tuple(a - b for a, b in zip(tuple_1, tuple_2))
print(f"Cách 2 - zip+comprehension: {result2}")

# Cách 3: operator.sub
import operator
result3 = tuple(map(operator.sub, tuple_1, tuple_2))
print(f"Cách 3 - operator.sub: {result3}")

# Cách 4: NumPy
import numpy as np
result4 = tuple(np.array(tuple_1) - np.array(tuple_2))
print(f"Cách 4 - numpy: {result4}")

Kết quả

Tuple 1: (7, 8, 11, 0, 3, 4)
Tuple 2: (3, 2, 22, 45, 12, 9)

Cách 1 - map+lambda: (4, 6, -11, -45, -9, -5)
Cách 2 - zip+comprehension: (4, 6, -11, -45, -9, -5)
Cách 3 - operator.sub: (4, 6, -11, -45, -9, -5)
Cách 4 - numpy: (4, 6, -11, -45, -9, -5)

Giải thích

  • zip(tuple_1, tuple_2) ghép cặp: (7,3), (8,2), (11,22), (0,45), (3,12), (4,9).
  • Mỗi cặp tính a - b.
  • zip dừng ở tuple ngắn hơn -> an toàn nếu độ dài khác nhau.
  • Kết quả tuple mới, tuple gốc không thay đổi (immutable).

Các phép toán element-wise khác

import operator

ops = {
    'add': operator.add,       # +
    'sub': operator.sub,       # -
    'mul': operator.mul,       # *
    'truediv': operator.truediv,  # /
    'floordiv': operator.floordiv, # //
    'mod': operator.mod,       # %
    'pow': operator.pow,       # **
}

def elementwise(t1, t2, op_name):
    op = ops[op_name]
    return tuple(map(op, t1, t2))

t1 = (10, 20, 30)
t2 = (3, 4, 5)

for name in ops:
    print(f"{name:10}: {elementwise(t1, t2, name)}")

Xử lý tuple độ dài khác nhau

from itertools import zip_longest

t1 = (10, 20, 30, 40)
t2 = (1, 2)

# zip_longest: điền fillvalue cho tuple ngắn hơn
result = tuple(a - b for a, b in zip_longest(t1, t2, fillvalue=0))
print(result)  # (9, 18, 30, 40) - phần tử thừa của t1 trừ 0

Trừ tuple từ scalar (broadcasting)

# Trừ 5 từ mỗi phần tử
t = (10, 20, 30)
result = tuple(x - 5 for x in t)
print(result)  # (5, 15, 25)

# NumPy broadcasting tự động
import numpy as np
print(tuple(np.array(t) - 5))  # (5, 15, 25)