เมื่อจำเป็นต้องลบทูเพิลที่มีค่าแรกที่ซ้ำกันออกจากชุดรายการทูเพิลที่กำหนด สามารถใช้ลูป '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' มันจะถูกเพิ่มไปยังชุด เช่นเดียวกับในรายการ
- นี่คือเอาต์พุตที่แสดงบนคอนโซล