โจทย์: มี 2 ลิสต์ของ Tuple (key, value) ต้องการรวม value ของ key เดียวกันจากทั้ง 2 ลิสต์
Input/Output
list_one = [('a', 2), ('b', 3), ('c', 5)]
list_two = [('c', 7), ('a', 4), ('b', 2)]
Output: [('a', 6), ('b', 5), ('c', 12)]
วิธีที่ 1: ใช้ Dictionary + Loop
list_one = [('a', 2), ('b', 3), ('c', 5)]
list_two = [('c', 7), ('a', 4), ('b', 2)]
result = dict(list_one)
for tup in list_two:
if tup[0] in result:
result[tup[0]] += tup[1]
print(list(result.items()))
[('a', 6), ('b', 5), ('c', 12)]
วิธีที่ 2: ใช้ collections.Counter (แนะนำ)
Counter รองรับการบวก (+) ระหว่าง Counter objects ได้โดยตรง
from collections import Counter
list_one = [('a', 2), ('b', 3), ('c', 5)]
list_two = [('c', 7), ('a', 4), ('b', 2)]
result = Counter(dict(list_one)) + Counter(dict(list_two))
print(list(result.items()))
[('a', 6), ('b', 5), ('c', 12)]
ข้อดีของ Counter: โค้ดสั้น 1 บรรทัด จัดการ key ที่ไม่มีอยู่ได้อัตโนมัติ (ถือเป็น 0) และรองรับการบวกหลาย Counter พร้อมกัน