Khi cần xóa tuple có giá trị đầu trùng lặp khỏi list tuple cho trước, có thể dùng vòng lặp 'for' đơn giản và phương thức 'add', 'append'.
Minh họa:
Ví dụ
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 a not in visited_data:
visited_data.add(a)
my_output_list.append((a, b))
print("List tuple là: ")
print(my_input)
print("List tuple sau khi xóa trùng lặp: ")
print(my_output_list)
Đầu ra
List tuple là: [(45.324, 'Hi Jane, how are you'), (34252.85832, 'Hope you are good'), (45.324, 'You are the best.')] List tuple sau khi xóa trùng lặp: [(45.324, 'Hi Jane, how are you'), (34252.85832, 'Hope you are good')]
Giải thích
- Định nghĩa list tuple, hiển thị.
- Tạo set rỗng và list rỗng.
- Duyệt list tuple, nếu chưa có trong 'set', thêm vào set và list.
- Hiển thị kết quả.