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

หาผลรวมกลุ่มของลิสต์ Tuple ใน Python


เมื่อต้องการหาผลรวมกลุ่มของลิสต์ของ Tuple ต้องใช้เมธอด 'Counter' และตัวดำเนินการ '+'

'Counter' เป็น sub-class ช่วยนับออบเจ็กต์ที่แฮชได้ คือสร้างแฮชเทเบิลเอง (ของ iterable เช่น ลิสต์, Tuple) เมื่อถูกเรียก

คืนค่า itertool สำหรับทุกองค์ประกอบที่มีค่า count ไม่ใช่ศูนย์

ตัวดำเนินการ '+' ใช้บวกค่าตัวเลข หรือต่อสตริง

ตัวอย่าง

from collections import Counter

my_list_1 = [('Hi', 14), ('there', 16), ('Jane', 28)]
my_list_2 = [('Jane', 12), ('Hi', 4), ('there', 21)]
print("The first list is : ")
print(my_list_1)
print("The second list is : ")
print(my_list_2)
cumulative_val_1 = Counter(dict(my_list_1))
cumulative_val_2 = Counter(dict(my_list_2))
cumulative_val_3 = cumulative_val_1 + cumulative_val_2
my_result = list(cumulative_val_3.items())
print("The grouped summation of list of tuple is : ")
print(my_result)

ผลลัพธ์

The first list is : [('Hi', 14), ('there', 16), ('Jane', 28)]
The second list is : [('Jane', 12), ('Hi', 4), ('there', 21)]
The grouped summation of list of tuple is : [('Hi', 18), ('there', 37), ('Jane', 40)]

คำอธิบาย

  • นำเข้าแพ็กเกจที่จำเป็น
  • กำหนดสองลิสต์ของ Tuple และแสดงบนคอนโซล
  • แปลงทั้งสองลิสต์ของ Tuple เป็นดิกชันนารี
  • บวกกันด้วยตัวดำเนินการ '+'
  • แปลงผลลัพธ์เป็นลิสต์ โดยใช้เฉพาะ 'values' ของดิกชันนารี
  • ข้อมูลจากการดำเนินการนี้ถูกเก็บในตัวแปร
  • ตัวแปรนี้คือเอาต์พุทที่แสดงบนคอนโซล