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

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

ภาพรวม

จาก list of lists ให้คัดเฉพาะแถวที่ element ทุกตัวในแถวนั้นปรากฏจำนวนครั้งเป็นเลขคู่ (2, 4, 6...)

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

my_list = [
    [10, 21, 34, 21, 37],
    [41, 41, 52, 68, 68, 41],
    [12, 29],
    [30, 30, 51, 51]
]

print("The list is:", my_list)

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

print("The result is:", my_result)

ผลลัพธ์

The list is: [[10, 21, 34, 21, 37], [41, 41, 52, 68, 68, 41], [12, 29], [30, 30, 51, 51]]
The result is: [[30, 30, 51, 51]]

คำอธิบายแต่ละแถว

RowElements & CountsAll Even?
[10, 21, 34, 21, 37]10:1, 21:2, 34:1, 37:1ไม่ (มีคี่)
[41, 41, 52, 68, 68, 41]41:3, 52:1, 68:2ไม่ (41=3, 52=1)
[12, 29]12:1, 29:1ไม่
[30, 30, 51, 51]30:2, 51:2ใช่

ประสิทธิภาพ

  • row.count(element) ในลูปทำให้ O(n²) ต่อแถว
  • แนะนำใช้ Counter(row) แทน: all(v % 2 == 0 for v in Counter(row).values())

เวอร์ชันที่ดีกว่า


from collections import Counter

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