Khi cần tìm giao (intersection) của dữ liệu trong các bản ghi tuple (list of tuples), có thể sử dụng list comprehension.
List comprehension là cách ngắn gọn để duyệt list và thực hiện phép toán.
Giao của hai tập hợp là các phần tử xuất hiện trong cả hai.
Ví dụ
# Hai list chứa các tuple bản ghi
list_1 = [('Hi', 1), ('there', 11), ('Will', 56)]
list_2 = [('Hi', 1), ('are', 7), ('you', 10)]
print("List 1:")
print(list_1)
print("\nList 2:")
print(list_2)
# Tìm giao: tuple xuất hiện trong CẢ HAI list
intersection = [elem for elem in list_1 if elem in list_2]
print("\nGiao của hai list of tuples:")
print(intersection)
Kết quả
List 1:
[('Hi', 1), ('there', 11), ('Will', 56)]
List 2:
[('Hi', 1), ('are', 7), ('you', 10)]
Giao của hai list of tuples:
[('Hi', 1)]
Giải thích
- Duyệt qua từng
elemtronglist_1. - Kiểm tra
elem in list_2(so sánh tuple hoàn chỉnh). - Chỉ giữ các tuple xuất hiện trong cả hai list.
- Kết quả là list chứa các tuple chung.
Cách hiệu quả hơn cho list lớn: Dùng set
# Chuyển sang set để lookup O(1) thay vì O(n) set_2 = set(list_2) intersection_fast = [elem for elem in list_1 if elem in set_2] # Hoặc dùng toán tử & cho set intersection_set = list(set(list_1) & set(list_2)) # Lưu ý: set không giữ thứ tự, kết quả có thể khác thứ tự gốc
Giao theo khóa cụ thể (key-based intersection)
# Chỉ so sánh theo phần tử đầu tiên (tên)
names_1 = {t[0] for t in list_1}
names_2 = {t[0] for t in list_2}
common_names = names_1 & names_2 # {'Hi'}
# Lấy toàn bộ tuple từ list_1 có tên trong common_names
result = [t for t in list_1 if t[0] in common_names]
print(result) # [('Hi', 1)]
Ứng dụng thực tế: Tìm user chung giữa hai hệ thống
users_system_a = [(1, 'alice', 'alice@email.com'), (2, 'bob', 'bob@email.com')]
users_system_b = [(10, 'alice', 'alice@work.com'), (20, 'charlie', 'charlie@email.com')]
# Giao theo email
emails_a = {u[2] for u in users_system_a}
emails_b = {u[2] for u in users_system_b}
common_emails = emails_a & emails_b
common_users = [u for u in users_system_a if u[2] in common_emails]
print(common_users) # [(1, 'alice', 'alice@email.com')]