Khi cần xóa các tuple trùng khớp từ hai list tuple, có thể dùng list comprehension.
List lưu trữ giá trị đa dạng. List tuple chứa các tuple bên trong list.
List comprehension là cách viết tắt duyệt list và thực hiện phép toán.
Minh họa:
Ví dụ
my_list_1 = [('Hi', 'there'), ('Jane', 'Hi'), ('how', 'are'), ('you', '!')]
my_list_2 = [('Hi', 'there'), ('Hi', 'Jane')]
print("List đầu tiên: ")
print(my_list_1)
print("List thứ hai: ")
print(my_list_2)
my_result = [sub for sub in my_list_1 if sub not in my_list_2]
print("List tuple sau lọc: ")
print(my_result)
Đầu ra
List đầu tiên:
[('Hi', 'there'), ('Jane', 'Hi'), ('how', 'are'), ('you', '!')]
List thứ hai:
[('Hi', 'there'), ('Hi', 'Jane')]
List tuple sau lọc:
[('Jane', 'Hi'), ('how', 'are'), ('you', '!')]
Giải thích
- Định nghĩa hai list tuple, hiển thị.
- Dùng list comprehension duyệt tuple.
- Lọc bỏ tuple có mặt ở cả hai list.
- Hiển thị các tuple còn lại.