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

Thay thế phần tử trùng lặp trong tuple Python

Khi cần thay thế các phần tử trùng lặp trong tuple bằng một giá trị cụ thể (ví dụ: 'FILL'), có thể dùng set để theo dõi phần tử đã thấy và list comprehension để xây dựng tuple mới.

Vì tuple bất biến, ta tạo tuple mới từ kết quả lọc.

Ví dụ

my_tuple = (11, 14, 0, 78, 33, 11, 10, 78, 0)
print(f"Tuple ban đầu: {my_tuple}")

seen = set()
# Duyệt tuple, nếu chưa thấy -> giữ nguyên, đã thấy -> thay bằng 'FILL'
result = tuple(elem if elem not in seen and not seen.add(elem) else 'FILL' 
               for elem in my_tuple)

print(f"Tuple sau khi thay thế trùng lặp: {result}")

Kết quả

Tuple ban đầu: (11, 14, 0, 78, 33, 11, 10, 78, 0)
Tuple sau khi thay thế trùng lặp: (11, 14, 0, 78, 33, 'FILL', 10, 'FILL', 'FILL')

Giải thích

  • seen là set rỗng ban đầu.
  • Biểu thức elem not in seen and not seen.add(elem):
    • Nếu elem chưa trong seen: elem not in seen là True, seen.add(elem) thêm vào set và trả về None (falsy), not None là True -> toàn bộ True -> giữ elem.
    • Nếu elem đã trong seen: elem not in seen là False -> short-circuit, không chạy seen.add() -> toàn bộ False -> thay bằng 'FILL'.
  • Kết quả chuyển thành tuple.

Cách dễ đọc hơn (khuyến nghị)

def replace_duplicates(tup, fill_value='FILL'):
    seen = set()
    result = []
    for elem in tup:
        if elem in seen:
            result.append(fill_value)
        else:
            seen.add(elem)
            result.append(elem)
    return tuple(result)

print(replace_duplicates(my_tuple))
print(replace_duplicates(my_tuple, fill_value=0))
print(replace_duplicates(my_tuple, fill_value=None))

Chỉ giữ lần xuất hiện đầu tiên (loại bỏ trùng lặp thuần túy)

def remove_duplicates_keep_first(tup):
    seen = set()
    return tuple(x for x in tup if not (x in seen or seen.add(x)))

print(remove_duplicates_keep_first(my_tuple))
# (11, 14, 0, 78, 33, 10)

Đếm số lần xuất hiện trước khi quyết định

from collections import Counter

counts = Counter(my_tuple)
# Chỉ thay thế nếu xuất hiện > 1 lần
result = tuple(elem if counts[elem] == 1 else 'FILL' for elem in my_tuple)
print(result)  # (11, 14, 0, 78, 33, 'FILL', 10, 'FILL', 'FILL')
# Giống kết quả trên nhưng logic rõ ràng hơn