เมื่อต้องการเรียง Tuple ตามจำนวนครั้งที่ค่าแรกปรากฏ สามารถใช้เมธอด dict.fromkeys ได้
ลิสต์สามารถเก็บค่าที่หลากหลายได้
ลิสต์ของ Tuple คือ Tuple ที่อยู่ภายในลิสต์
เมธอด 'dict.fromkeys' จะคืนค่าดิกชันนารีพร้อม key และ value เฉพาะ
ตัวอย่าง
def sort_on_occurence(my_lst):
my_dict = {}
for i, j in my_lst:
my_dict.setdefault(i, []).append(j)
return [(i, *dict.fromkeys(j), len(j)) for i, j in my_dict.items()]
my_list = [(1, 'Harold'), (12, 'Jane'), (4, 'Paul'), (7, 'Will')]
print("The list of tuples is")
print(my_list)
print("The list after sorting by occurence is")
print(sort_on_occurence(my_list))
ผลลัพธ์
The list of tuples is [(1, 'Harold'), (12, 'Jane'), (4, 'Paul'), (7, 'Will')] The list after sorting by occurence is [(1, 'Harold', 1), (12, 'Jane', 1), (4, 'Paul', 1), (7, 'Will', 1)]
คำอธิบาย
- กำหนดเมธอด 'sort_on_occurence' รับลิสต์ของ Tuple เป็นพารามิเตอร์
- สร้างดิกชันนารีใหม่
- วนลูปลิสต์ของ Tuple และตั้งค่า default ภายในดิกชันนารีว่าง
- กำหนดลิสต์ของ Tuple และแสดงบนคอนโซล
- เรียกฟังก์ชันโดยส่งลิสต์ของ Tuple ที่กำหนดข้างต้น
- นี่คือเอาต์พุทที่แสดงบนคอนโซล