Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Lọc tuple theo sự hiện diện của phần tử list trong Python

Khi cần lọc các tuple trong list dựa trên việc chứa phần tử từ một target list, có thể dùng list comprehension với any().

any() trả về True nếu ít nhất một phần tử trong iterable là True.

Ví dụ

# List chứa các tuple
my_list = [(11, 14), (54, 56, 87), (98, 0, 10), (13, 76)]
# Target list: các giá trị cần tìm
target_list = [34, 11]

print(f"List gốc: {my_list}")
print(f"Target list: {target_list}")

# Lọc: giữ tuple nếu CÓ ÍT NHẤT 1 phần tử nằm trong target_list
filtered = [tup for tup in my_list if any(elem in target_list for elem in tup)]

print(f"\nKết quả lọc: {filtered}")

# Giải thích từng tuple:
for tup in my_list:
    has_match = any(elem in target_list for elem in tup)
    print(f"  {tup} -> {'Giữ' if has_match else 'Loại'} (common: {set(tup) & set(target_list)})")

Kết quả

List gốc: [(11, 14), (54, 56, 87), (98, 0, 10), (13, 76)]
Target list: [34, 11]

Kết quả lọc: [(11, 14)]

Giải thích từng tuple:
  (11, 14) -> Giữ (common: {11})
  (54, 56, 87) -> Loại (common: set())
  (98, 0, 10) -> Loại (common: set())
  (13, 76) -> Loại (common: set())

Giải thích

  • any(elem in target_list for elem in tup): kiểm tra từng phần tử của tuple xem có trong target_list không.
  • Tuple (11, 14) có 11 nằm trong target_list -> giữ lại.
  • Các tuple khác không có phần tử nào trùng -> loại bỏ.

Biến thể: Lọc tuple chứa TẤT CẢ phần tử target (AND logic)

# Giữ tuple nếu CHỨA HẾT các phần tử trong target_list
filtered_all = [tup for tup in my_list if all(elem in tup for elem in target_list)]
print(filtered_all)  # [] - không tuple nào chứa cả 34 và 11

Tối ưu hiệu năng: Chuyển target_list thành set

target_set = set(target_list)  # Lookup O(1) thay vì O(n)
filtered = [tup for tup in my_list if any(elem in target_set for elem in tup)]

Lọc theo index cụ thể

# Chỉ kiểm tra phần tử index 0
filtered_idx = [tup for tup in my_list if tup[0] in target_list]
print(filtered_idx)  # [(11, 14)]

Lọc tuple KHÔNG chứa phần tử nào trong target (NOT IN)

filtered_none = [tup for tup in my_list if not any(elem in target_set for elem in tup)]
print(filtered_none)  # [(54, 56, 87), (98, 0, 10), (13, 76)]

Ứng dụng thực tế: Lọc log entries

logs = [
    ('ERROR', 'Connection timeout', 1001),
    ('INFO', 'User login', 1002),
    ('WARN', 'High memory', 1003),
    ('ERROR', 'Disk full', 1004),
]

error_codes = {1001, 1004}
error_logs = [log for log in logs if log[2] in error_codes]
print(error_logs)
# [('ERROR', 'Connection timeout', 1001), ('ERROR', 'Disk full', 1004)]