เมื่อต้องการลบ Tuple ที่มีค่าแรกซ้ำจากลิสต์ของ Tuple ที่กำหนด สามารถใช้ลูป 'for' ธรรมดา และเมธอด 'add' และ 'append' ได้
ตัวอย่าง
my_input = [(45.324, 'Hi Jane, how are you'), (34252.85832, 'Hope you are good'), (45.324, 'You are the best.')]
visited_data = set()
my_output_list = []
for a, b in my_input:
if not a in visited_data:
visited_data.add(a)
my_output_list.append((a, b))
print("The list of tuple is : ")
print(my_input)
print("The list of tuple after removing duplicates is :")
print(my_output_list)
ผลลัพธ์
The list of tuple is : [(45.324, 'Hi Jane, how are you'), (34252.85832, 'Hope you are good'), (45.324, 'You are the best.')] The list of tuple after removing duplicates is : [(45.324, 'Hi Jane, how are you'), (34252.85832, 'Hope you are good')]
คำอธิบาย
- กำหนดลิสต์ของ Tuple และแสดงบนคอนโซล
- สร้าง set ว่าง และลิสต์ว่าง
- วนลูปลิสต์ของ Tuple หากไม่ได้อยู่ใน 'set' ให้เพิ่มเข้า set และลิสต์
- นี่คือเอาต์พุทที่แสดงบนคอนโซล