เมื่อต้องการนับค่าที่ไม่ซ้ำกันในลิสต์ของ tuple ใช้ 'defaultdict', ตัวดำเนินการ 'set' และเมธอด 'append'
ตัวอย่าง
สาธิตด้านล่าง:
from collections import defaultdict
my_list = [(12, 32), (12, 21), (21, 32), (89, 21), (71, 21), (89, 11), (99, 10), (8, 23), (10, 23)]
print("The list is :")
print(my_list)
my_result = defaultdict(list)
for element in my_list:
my_result[element[1]].append(element[0])
my_result = dict(my_result)
result_dictionary = dict()
for key in my_result:
result_dictionary[key] = len(list(set(my_result[key])))
print("The resultant list is :")
print(result_dictionary)
ผลลัพธ์
The list is : [(12, 32), (12, 21), (21, 32), (89, 21), (71, 21), (89, 11), (99, 10), (8, 23), (10, 23)]
The resultant list is : {32: 2, 21: 3, 11: 1, 10: 1, 23: 2}
คำอธิบาย
- นำเข้าแพ็กเกจที่จำเป็น
- กำหนดลิสต์ของ tuple และแสดงผล
- สร้าง dictionary ว่างด้วย defaultdict
- วนลูปลิสต์ นำ element ที่ 2 และ 1 ไป append ใน dictionary
- แปลงลิสต์กลับเป็น dictionary
- สร้าง dictionary ว่างอีกตัว
- วนลูปลิสต์ ใช้ 'set' หาค่าที่ไม่ซ้ำ แปลงเป็นลิสต์แล้วหาความยาว
- แสดงผลลัพธ์บนคอนโซล