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

การหา Combinations ของ Sum ระหว่าง Tuple ใน List of Tuples Python

Combinations of Sum with Tuples in Tuple List

เมื่อต้องการหา Combinations ของผลบวก (Sum) ระหว่าง Tuple ใน List of Tuples สามารถใช้ itertools.combinations และ List Comprehension ได้

itertools.combinations

combinations(iterable, r) คืน Subsequence ความยาว r จาก Iterable แบบ Lexicographic Sort Order

ตัวอย่างโค้ด

from itertools import combinations

my_list = [(67, 45), (34, 56), (99, 123), (10, 56)]
print("The list of tuple is : ")
print(my_list)

# combinations(my_list, 2) -> เลือก 2 Tuple ต่อคู่
# (a1, a2), (b1, b2) -> บวกกัน (b1+a1, b2+a2)
my_result = [(b1 + a1, b2 + a2) for (a1, a2), (b1, b2) in combinations(my_list, 2)]

print("The summation combination result is : ")
print(my_result)

ผลลัพธ์

The list of tuple is : [(67, 45), (34, 56), (99, 123), (10, 56)]
The summation combination result is : [(101, 101), (166, 168), (77, 101), (133, 179), (44, 112), (109, 179)]

คำอธิบาย

  • Import combinations จาก itertools
  • กำหนด List of Tuples (แต่ละ Tuple มี 2 Element) และแสดงผล
  • combinations(my_list, 2) สร้างคู่ Tuple ทั้งหมด 6 คู่ (4C2 = 6)
  • List Comprehension Unpack Tuple เป็น (a1, a2), (b1, b2) แล้วบวกกัน
  • เก็บผลลัพธ์และแสดง

6 คู่ที่เกิดขึ้น (Combinations)

PairTuple 1Tuple 2Sum (Elem 0)Sum (Elem 1)Result
1(67, 45)(34, 56)67+34=10145+56=101(101, 101)
2(67, 45)(99, 123)67+99=16645+123=168(166, 168)
3(67, 45)(10, 56)67+10=7745+56=101(77, 101)
4(34, 56)(99, 123)34+99=13356+123=179(133, 179)
5(34, 56)(10, 56)34+10=4456+56=112(44, 112)
6(99, 123)(10, 56)99+10=109123+56=179(109, 179)

Generalize สำหรับ Tuple ความยาว N

from itertools import combinations

def sum_combinations(tuple_list, r=2):
    """Sum of r tuples element-wise"""
    result = []
    for combo in combinations(tuple_list, r):
        # Zip ทุก Tuple ใน Combo แล้ว Sum แต่ละ Column
        summed = tuple(sum(vals) for vals in zip(*combo))
        result.append(summed)
    return result

my_list = [(67, 45), (34, 56), (99, 123), (10, 56)]
print(sum_combinations(my_list, 2))  # r=2
print(sum_combinations(my_list, 3))  # r=3 (3 tuples per combo)

ใช้ NumPy

import numpy as np
from itertools import combinations

arr = np.array(my_list)
result = [tuple(np.sum(combo, axis=0)) for combo in combinations(arr, 2)]
print(result)