Cumulative Nested Tuple Column Product
เมื่อต้องการหา Column Product แบบสะสม (Cumulative) ของ Nested Tuple (Tuple ของ Tuples) ใช้ zip() และ Nested Generator Expression
ตัวอย่างโค้ด
tuple_1 = ((11, 23), (41, 25), (22, 19))
tuple_2 = ((60, 73), (31, 91), (14, 14))
print("The first tuple is : ")
print(tuple_1)
print("The second tuple is : ")
print(tuple_2)
# Nested zip: ระดับนอกจับคู่ Tuple, ระดับในจับคู่ Element
my_result = tuple(
tuple(a * b for a, b in zip(tup_1, tup_2))
for tup_1, tup_2 in zip(tuple_1, tuple_2)
)
print("The tuple after product is : ")
print(my_result)
ผลลัพธ์
The first tuple is : ((11, 23), (41, 25), (22, 19)) The second tuple is : ((60, 73), (31, 91), (14, 14)) The tuple after product is : ((660, 1679), (1271, 2275), (308, 266))
คำอธิบาย
- กำหนด Nested Tuple 2 ตัว (3 Rows × 2 Cols) และแสดงผล
- Outer
zip(tuple_1, tuple_2)จับคู่ Row: ((11,23), (60,73)), ... - Inner
zip(tup_1, tup_2)จับคู่ Column: (11,60), (23,73) - Generator Expression คูณ
a * bแต่ละคู่ - Inner
tuple(...)สร้าง Row ใหม่ - Outer
tuple(...)สร้าง Nested Tuple ใหม่ - แสดงผล
การคำนวณแบบละเอียด
| Row | Tuple 1 | Tuple 2 | Element-wise Product |
|---|---|---|---|
| 0 | (11, 23) | (60, 73) | (11×60, 23×73) = (660, 1679) |
| 1 | (41, 25) | (31, 91) | (41×31, 25×91) = (1271, 2275) |
| 2 | (22, 19) | (14, 14) | (22×14, 19×14) = (308, 266) |
ใช้ NumPy (แนะนำสำหรับ Matrix Operations)
import numpy as np
t1 = np.array(((11, 23), (41, 25), (22, 19)))
t2 = np.array(((60, 73), (31, 91), (14, 14)))
# Element-wise Multiplication (Hadamard Product)
result = t1 * t2
print(result)
# [[ 660 1679]
# [1271 2275]
# [ 308 266]]
# แปลงกลับ Tuple
result_tuple = tuple(tuple(row) for row in result)
print(result_tuple) # ((660, 1679), (1271, 2275), (308, 266))
Generalize: ใช้ map + operator.mul
from operator import mul
# สำหรับ Flat Tuple
flat_result = tuple(map(mul, t1, t2))
# สำหรับ Nested
nested_result = tuple(tuple(map(mul, r1, r2)) for r1, r2 in zip(tuple_1, tuple_2))
print(nested_result)