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

Python – Extract Matrix Rows ที่ Element ทุกตัวมีความถี่เป็นเลขคู่

ภาพรวม

จาก matrix (list of lists) ให้คัดเฉพาะแถวที่ ทุก unique element ในแถวนั้นมีความถี่เป็นเลขคู่

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


from collections import Counter

my_list = [
    [41, 25, 25, 62],
    [41, 41, 41, 41, 22, 22],
    [65, 57, 65, 57],
    [11, 24, 36, 48]
]

print("The list is:", my_list)

my_result = [
    row for row in my_list
    if all(count % 2 == 0 for count in Counter(row).values())
]

print("The result is:", my_result)

ผลลัพธ์

The list is: [[41, 25, 25, 62], [41, 41, 41, 41, 22, 22], [65, 57, 65, 57], [11, 24, 36, 48]]
The result is: [[41, 41, 41, 41, 22, 22], [65, 57, 65, 57]]

คำอธิบาย

RowCountsAll Even?
[41, 25, 25, 62]41:1, 25:2, 62:1ไม่ (41,62 เป็นคี่)
[41, 41, 41, 41, 22, 22]41:4, 22:2ใช่
[65, 57, 65, 57]65:2, 57:2ใช่
[11, 24, 36, 48]11:1, 24:1, 36:1, 48:1ไม่ (ทั้งหมดคี่)

ประสิทธิภาพ

  • ใช้ Counter นับครั้งเดียวต่อแถว O(n)
  • ดีกว่า row.count() ในลูปที่เป็น O(n²)

Pandas Version


import pandas as pd
df = pd.DataFrame(my_list)
mask = df.apply(lambda row: all(row.value_counts() % 2 == 0), axis=1)
result = df[mask].values.tolist()