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

Tổng các phần tử tuple trong list Python

Khi cần tính tổng tất cả các phần tử trong list of tuples, có thể dùng sum() lồng nhau hoặc map(sum, ...).

Hàm sum() cộng dồn các phần tử trong iterable.

Hàm map() áp dụng hàm cho mỗi phần tử.

Ví dụ

my_list = [(11, 14), (54, 56), (98, 0), (13, 76)]
print(f"List of tuples: {my_list}")

# Cách 1: sum(map(sum, ...)) - ngắn gọn
# map(sum, my_list) -> iterator của tổng từng tuple: 25, 110, 98, 89
# sum(...) cộng tổng các giá trị đó
total = sum(map(sum, my_list))
print(f"\nCách 1 - sum(map(sum, ...)): {total}")

# Cách 2: Generator expression (dễ đọc hơn)
total2 = sum(sum(tup) for tup in my_list)
print(f"Cách 2 - sum(sum(tup) for tup): {total2}")

# Cách 3: itertools.chain (làm phẳng rồi sum)
from itertools import chain
total3 = sum(chain.from_iterable(my_list))
print(f"Cách 3 - chain.from_iterable: {total3}")

# Cách 4: Vòng lặp truyền thống
total4 = 0
for tup in my_list:
    for val in tup:
        total4 += val
print(f"Cách 4 - nested loop: {total4}")

Kết quả

List of tuples: [(11, 14), (54, 56), (98, 0), (13, 76)]

Cách 1 - sum(map(sum, ...)): 322
Cách 2 - sum(sum(tup) for tup): 322
Cách 3 - chain.from_iterable: 322
Cách 4 - nested loop: 322

Giải thích

  • map(sum, my_list) tính tổng từng tuple: 11+14=25, 54+56=110, 98+0=98, 13+76=89.
  • sum(...) ngoài cùng cộng: 25+110+98+89=322.
  • Cách 2 dùng generator expression (sum(tup) for tup in my_list) dễ hiểu hơn.
  • itertools.chain.from_iterable làm phẳng list of tuples thành iterator đơn trước khi sum.

Tính tổng theo cột (column-wise sum)

# Giả sử tất cả tuple cùng độ dài
data = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]

# zip(*data) transpose: [(1,4,7), (2,5,8), (3,6,9)]
col_sums = tuple(sum(col) for col in zip(*data))
print(f"Tổng theo cột: {col_sums}")  # (12, 15, 18)

# Với numpy (hiệu quả cho dữ liệu lớn)
import numpy as np
arr = np.array(data)
print(f"NumPy column sum: {arr.sum(axis=0)}")  # [12 15 18]

Tính tổng có điều kiện

# Chỉ cộng các số chẵn
even_sum = sum(val for tup in my_list for val in tup if val % 2 == 0)
print(f"Tổng số chẵn: {even_sum}")  # 14+54+56+98+0+76 = 298

# Chỉ cộng tuple có tổng > 100
large_tuple_sum = sum(sum(t) for t in my_list if sum(t) > 100)
print(f"Tổng các tuple lớn: {large_tuple_sum}")  # 110 + 98 = 208

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

from itertools import zip_longest

uneven = [(1, 2), (3, 4, 5), (6,)]
# zip_longest fillvalue=0 cho phép sum cột
col_sums = [sum(filter(None.__ne__, col)) for col in zip_longest(*uneven, fillvalue=0)]
print(col_sums)  # [10, 6, 5]