Maximum of Similar Indices in Two Lists of Tuples
เมื่อต้องการหาค่าสูงสุดของ Index ที่ตรงกันใน List of Tuples สอง List สามารถใช้ zip() และ List Comprehension ได้
ตัวอย่างโค้ด
my_list_1 = [(67, 45), (34, 56), (99, 123)]
my_list_2 = [(10, 56), (45, 0), (100, 12)]
print("The first list is : ")
print(my_list_1)
print("The second list is : ")
print(my_list_2)
# zip จับคู่ Tuple คู่กัน แล้วหา Max ของแต่ละ Index
my_result = [(max(x[0], y[0]), max(x[1], y[1]))
for x, y in zip(my_list_1, my_list_2)]
print("The maximum value among the two lists is :")
print(my_result)
ผลลัพธ์
The first list is : [(67, 45), (34, 56), (99, 123)] The second list is : [(10, 56), (45, 0), (100, 12)] The maximum value among the two lists is : [(67, 56), (45, 56), (100, 123)]
คำอธิบาย
- กำหนด List of Tuples 2 ตัว และแสดงผล
zip(my_list_1, my_list_2)จับคู่ Tuple ตำแหน่งเดียวกัน: ( (67,45), (10,56) ), ...- List Comprehension: สำหรับแต่ละคู่ (x, y) หา max ของ Index 0 และ Index 1 แยกกัน
- สร้าง Tuple ใหม่จากค่า Max ทั้งสอง
- แสดงผล
การคำนวณแบบละเอียด
| Pair Index | List 1 | List 2 | Max Index 0 | Max Index 1 | Result |
|---|---|---|---|---|---|
| 0 | (67, 45) | (10, 56) | max(67,10)=67 | max(45,56)=56 | (67, 56) |
| 1 | (34, 56) | (45, 0) | max(34,45)=45 | max(56,0)=56 | (45, 56) |
| 2 | (99, 123) | (100, 12) | max(99,100)=100 | max(123,12)=123 | (100, 123) |
ขยายสำหรับ Tuple ความยาวไม่คงที่
def max_tuples(t1, t2):
"""Handle tuples of different lengths"""
return tuple(max(a, b) for a, b in zip(t1, t2))
# ใช้กับ List of Tuples
result = [max_tuples(x, y) for x, y in zip(my_list_1, my_list_2)]
print(result)
ใช้ NumPy (เร็วกว่าสำหรับข้อมูลมาก)
import numpy as np
arr1 = np.array(my_list_1)
arr2 = np.array(my_list_2)
result = np.maximum(arr1, arr2)
print(result.tolist()) # [[67, 56], [45, 56], [100, 123]]