Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - ลบคอลัมน์ที่มีสมาชิกซ้ำใน Matrix (List of Lists)

ลบคอลัมน์ (Index แนวตั้ง) ที่มีค่าซ้ำกันใน Matrix โดยตรวจสอบแนวตั้ง (Column-wise) ว่ามีค่าซ้ำหรือไม่

ตัวอย่างโค้ด

from itertools import chain

def remove_dupes(my_sub):
    my_string = set()
    for i, elem in enumerate(my_sub):
        if elem not in my_string:
            my_string.add(elem)
        else:
            yield i

my_list = [[5, 1, 6, 7, 9], [6, 3, 1, 9, 1], [4, 2, 9, 8, 9], [5, 1, 6, 7, 3]]
print("The list is : ")
print(my_list)

K = 3
temp_idxs = set(chain.from_iterable(remove_dupes(sub) for sub in my_list))
my_result = [[elem for i, elem in enumerate(sub) if i not in temp_idxs] for sub in my_list]

print("The result is : ")
print(my_result)

ผลลัพธ์

The list is : [[5, 1, 6, 7, 9], [6, 3, 1, 9, 1], [4, 2, 9, 8, 9], [5, 1, 6, 7, 3]]
The result is : [[5, 1, 6, 7], [6, 3, 1, 9], [4, 2, 9, 8], [5, 1, 6, 7]]

คำอธิบาย

  • remove_dupes Generator: Yield Index ที่มีค่าซ้ำใน Row นั้น (แนวนอน)
  • chain.from_iterable รวม Index ซ้ำจากทุก Row
  • สร้าง Set temp_idxs ของ Column Index ที่มีซ้ำใน Row ใด Row หนึ่ง
  • List Comprehension: สร้าง Row ใหม่ เก็บเฉพาะ Index ที่ ไม่อยู่ ใน temp_idxs
  • ผล: Column 4 (Index 4) ถูกลบ เพราะมีค่าซ้ำใน Row 1 (9,9) และ Row 2 (9,9)