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

Python – ตรวจสอบแถวซ้ำ (Duplicate Rows) ใน Matrix ด้วย Counter

ภาพรวม

หาแถวที่ซ้ำกันใน Matrix (list of lists) โดยแปลงแต่ละแถวเป็น tuple แล้วนับความถี่ด้วย collections.Counter

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

from collections import Counter

def find_dupes(my_matrix):
    # แปลงแต่ละแถวเป็น tuple (hashable)
    row_tuples = map(tuple, my_matrix)
    freq_dict = Counter(row_tuples)
    
    for row, freq in freq_dict.items():
        if freq > 1:
            print(row)

my_matrix = [
    [1, 1, 0, 1, 0, 1],
    [0, 0, 1, 0, 0, 1],
    [1, 0, 1, 1, 0, 0],
    [1, 1, 0, 1, 0, 1],  # ซ้ำแถวแรก
    [0, 0, 1, 0, 0, 1],  # ซ้ำแถวที่สอง
    [0, 0, 1, 0, 0, 1]   # ซ้ำแถวที่สอง (รวม 3 ครั้ง)
]

print("The matrix is:")
for row in my_matrix:
    print(row)

print("\nThe result is:")
find_dupes(my_matrix)

ผลลัพธ์

The matrix is:
[1, 1, 0, 1, 0, 1]
[0, 0, 1, 0, 0, 1]
[1, 0, 1, 1, 0, 0]
[1, 1, 0, 1, 0, 1]
[0, 0, 1, 0, 0, 1]
[0, 0, 1, 0, 0, 1]

The result is:
(1, 1, 0, 1, 0, 1)
(0, 0, 1, 0, 0, 1)

คำอธิบาย

  • List ไม่ hashable ไม่สามารถเป็น key ของ dict/Counter ได้ -> แปลงเป็น tuple
  • Counter นับความถี่อัตโนมัติ
  • กรองเฉพาะ freq > 1

วิธีอื่น: ใช้ Pandas

import pandas as pd
df = pd.DataFrame(my_matrix)
duplicates = df[df.duplicated(keep=False)]
print(duplicates)