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

Python – Loại bỏ phần tử list 2 tại các index trùng lặp của list 1

Giới thiệu

Cho hai list cùng độ dài. Tìm các index trong list 1 có giá trị trùng lặp (xuat hiện lần 2 trở đi), sau đó loại bỏ các phần tử tại những index đó trong list 2.

Ví dụ minh họa

my_list_1 = [4, 5, 6, 5, 4, 7, 8, 6]
my_list_2 = [1, 7, 6, 4, 7, 9, 10, 11]

print("List 1:", my_list_1)
print("List 2:", my_list_2)

temp_set = set()
temp = []
for index, value in enumerate(my_list_1):
    if value not in temp_set:
        temp_set.add(value)
    else:
        temp.append(index)

my_result = [element for index, element in enumerate(my_list_2) if index not in temp]
print("List 2 sau khi loại bỏ index trùng lặp của list 1:")
print(my_result)

Kết quả đầu ra

List 1: [4, 5, 6, 5, 4, 7, 8, 6]
List 2: [1, 7, 6, 4, 7, 9, 10, 11]
List 2 sau khi loại bỏ index trùng lặp của list 1:
[1, 7, 6, 9, 10]

Giải thích

  • Duyệt list_1 với enumerate, dùng set temp_set theo dõi giá trị đã thấy.
  • Nếu giá trị đã có trong set -> index đó là duplicate, thêm vào list temp.
  • List comprehension lọc list_2: chỉ giữ phần tử nếu index không trong temp.
  • Index trùng lặp của list_1: 3 (5), 4 (4), 7 (6) -> loại bỏ index 3,4,7 của list_2 (giá trị 4,7,11).