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

การจัดกลุ่ม Tuple ในลิสต์ตามค่าตัวแรก (First Value) ใน Python

โจทย์: ให้ลิสต์ของ Tuple จัดกลุ่ม Tuple ที่มีค่าตัวแรก (Index 0) เหมือนกัน โดยรวมค่าต่อจากตัวแรกเข้าด้วยกัน

Input/Output

Input:  [(1, 2, 3), (1, 4, 5), (3, 4, 1), (3, 4, 2)]
Output: [(1, 2, 3, 4, 5), (3, 4, 1, 4, 2)]

วิธีแก้: ใช้ Dictionary + Tuple Unpacking

tuples = [(1, 2, 3), (1, 4, 5), (3, 4, 1), (3, 4, 2)]

result = {}
for sub_tuple in tuples:
    if sub_tuple[0] in result:
        result[sub_tuple[0]] = (*result[sub_tuple[0]], *sub_tuple[1:])
    else:
        result[sub_tuple[0]] = sub_tuple

print(list(result.values()))

ผลลัพธ์

[(1, 2, 3, 4, 5), (3, 4, 1, 4, 2)]

เทคนิคสำคัญ: (*result[key], *sub_tuple[1:]) ใช้ Unpacking operator (*) รวม Tuple เดิม (รวมตัวแรก) กับ Tuple ใหม่ (ตัดตัวแรกออก) ได้ Tuple ใหม่ยาวขึ้น

การประยุกต์: ใช้รวมข้อมูลที่มี Key เดียวกัน เช่น รวม Transaction ตาม User ID, รวม Log ตาม Session ID