ตัวอย่าง
โค้ดด้านล่างกรอง tuple ในลิสต์ ให้เก็บเฉพาะ tuple แรกของแต่ละค่าแรก (first element) โดยใช้ dictionary นับความถี่
my_list = [(21, 24), (13, 42), (11, 23), (32, 43), (25, 56), (73, 84), (91, 40), (40, 83), (13, 27)]
print("The list is :")
print(my_list)
my_key = 1
my_result = []
mems = dict()
for sub in my_list:
if sub[0] not in mems.keys():
mems[sub[0]] = 1
else:
mems[sub[0]] += 1
if mems[sub[0]] <= my_key:
my_result.append(sub)
print("The filtered tuples are :")
print(my_result)
ผลลัพธ์
The list is : [(21, 24), (13, 42), (11, 23), (32, 43), (25, 56), (73, 84), (91, 40), (40, 83), (13, 27)] The filtered tuples are : [(21, 24), (13, 42), (11, 23), (32, 43), (25, 56), (73, 84), (91, 40), (40, 83)]
คำอธิบาย
กำหนดลิสต์ tuple และแสดงผล
กำหนด my_key = 1 (จำนวนสูงสุดต่อค่าแรก)
ใช้ dictionary mems นับจำนวนครั้งที่ค่าแรกปรากฏ
ถ้าความถี่ <= my_key ให้เพิ่ม tuple เข้า result
แสดง tuple ที่กรองแล้ว