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

Tổng cột của tuple trong Python


Cho danh sách các tuple, tính tổng các phần tử cùng cột (cùng vị trí) giữa các tuple tương ứng.

Dùng for loop và zip

Dùng zip(*) để nhóm theo cột, sum từng nhóm, tạo tuple mới.

Ví dụ

data = [[(3, 92), (21, 4), (15, 6)],[(25, 62), (12, 7), (15, 7)]] 
print("The list of tuples: " + str(data)) 
result = [tuple(sum(m) for m in zip(*n)) for n in zip(*data)] 
print(" Column summation of tuples: " + str(result))

Đầu ra

The list of tuples: [[(3, 92), (21, 4), (15, 6)], [(25, 62), (12, 7), (15, 7)]] 
Column summation of tuples: [(28, 154), (33, 11), (30, 13)]

Dùng map và zip

Thay comprehension bằng map(sum, zip(*n)).

Ví dụ

data = [[(3, 92), (21, 4), (15, 6)],[(25, 62), (12, 7), (15, 7)]] 
print("The list of tuple values: " + str(data)) 
result = [tuple(map(sum, zip(*n))) for n in zip(*data)] 
print(" Column summation of tuples: " + str(result))

Đầu ra

The list of tuple values: [[(3, 92), (21, 4), (15, 6)], [(25, 62), (12, 7), (15, 7)]] 
Column summation of tuples: [(28, 154), (33, 11), (30, 13)]