K-th Column Product ใน List of Tuples
เมื่อต้องการหาผลคูณ (Product) ของ Column ที่ K ใน List of Tuples ใช้ List Comprehension และ Loop ธรรมดา
ตัวอย่างโค้ด
def prod_compute(my_val):
"""คำนวณผลคูณของ Iterable"""
my_result = 1
for elem in my_val:
my_result *= elem
return my_result
my_list = [(51, 62, 75), (18, 39, 25), (81, 19, 99)]
print("The list is : ")
print(my_list)
K = 2
print("The value of 'K' has been initialized")
# ดึง Column K ทุก Tuple แล้วหาผลคูณ
my_result = prod_compute([sub[K] for sub in my_list])
print("The product of the 'K'th Column of the list of tuples is : ")
print(my_result)
ผลลัพธ์
The list is : [(51, 62, 75), (18, 39, 25), (81, 19, 99)] The value of 'K' has been initialized The product of the 'K'th Column of the list of tuples is : 185625
คำอธิบาย
- สร้าง Function
prod_computeคำนวณผลคูณ (Initialize 1, Loop คูณสะสม) - กำหนด List of Tuples (3 Columns) และแสดงผล
- กำหนด K = 2 (Column Index 2 = ตัวที่ 3)
[sub[K] for sub in my_list]ดึง Column 2:[75, 25, 99]- ส่งเข้า
prod_compute→ 75 × 25 × 99 = 185,625 - แสดงผล
การคำนวณ
Column 2 (Index 2): 75, 25, 99
Product: 75 × 25 = 1,875
1,875 × 99 = 185,625
วิธีอื่น: ใช้ math.prod (Python 3.8+)
import math
my_list = [(51, 62, 75), (18, 39, 25), (81, 19, 99)]
K = 2
# สั้นและเร็วที่สุด
column_values = [sub[K] for sub in my_list]
my_result = math.prod(column_values)
print(my_result) # 185625
ใช้ functools.reduce
from functools import reduce
from operator import mul
my_result = reduce(mul, (sub[K] for sub in my_list), 1)
print(my_result) # 185625
ใช้ NumPy
import numpy as np
arr = np.array(my_list)
print(np.prod(arr[:, K])) # 185625
Generalize: Product ของทุก Column
import math
my_list = [(51, 62, 75), (18, 39, 25), (81, 19, 99)]
# Transpose แล้วหา Product แต่ละ Column
columns = list(zip(*my_list)) # [(51,18,81), (62,39,19), (75,25,99)]
products = [math.prod(col) for col in columns]
print(products) # [74418, 45942, 185625]
Error Handling: Index Out of Range
def safe_column_product(tuple_list, k):
try:
return math.prod(t[k] for t in tuple_list)
except IndexError:
raise ValueError(f"Column index {k} out of range for some tuples")
print(safe_column_product(my_list, 2)) # 185625
# safe_column_product(my_list, 5) # ValueError