เมื่อต้องการหาจำนวนครั้งที่เกิดขึ้นสำหรับแต่ละค่าของคีย์เฉพาะ ใช้ list comprehension และเมธอด lambda
สาธิตด้านล่าง:
ตัวอย่าง
from itertools import groupby
my_dict = [{'pyt' : 13, 'fun' : 44}, {'pyt' : 63, 'best' : 15}, {'pyt' : 24, 'fun' : 34}, {'pyt' : 47, 'best' : 64} ]
print("The dictionary is :")
print(my_dict)
my_key = 'pyt'
print("The key value is :")
print(my_key)
my_result = [{keys: len(list(value))} for keys, value in groupby(my_dict, lambda index: index[my_key])]
print("The result is :")
print(my_result)
ผลลัพธ์
The dictionary is : [{'pyt': 13, 'fun': 44}, {'pyt': 63, 'best': 15}, {'pyt': 24, 'fun': 34}, {'pyt': 47, 'best': 64}]
The key value is : pyt
The result is : [{13: 1}, {63: 1}, {24: 1}, {47: 1}]
คำอธิบาย
- นำเข้าแพ็กเกจที่จำเป็น
- กำหนดลิสต์ของ dictionary และแสดงผล
- กำหนดค่า key และแสดงผล
- ใช้ list comprehension วนลูป แปลงเป็นลิสต์ ใช้ 'groupby' จัดกลุ่ม element ของ dictionary และ index ของ key
- กำหนดให้ตัวแปร
- แสดงผลลัพธ์บนคอนโซล