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

Find Most Common Element ใน 2D List Python: หาสมาชิกที่พบบ่อยที่สุดในลิสต์ซ้อน

ได้ 2D List (ลิสต์ของลิสต์) หาสมาชิกที่ปรากฏบ่อยที่สุดรวมทุกสับลิสต์

วิธี 1: Flatten ด้วย List Comprehension + max/count

def highest_freq(lst):
    flat = [el for sub in lst for el in sub]
    return max(flat, key=flat.count)

listA = [[45,20,11],[20,17,45],[20,13,9]]
print(highest_freq(listA))  # 20

วิธี 2: ใช้ itertools.chain Flatten

from itertools import chain
def highest_freq(lst):
    flat = list(chain.from_iterable(lst))
    return max(flat, key=flat.count)

วิธี 3: ใช้ Counter + chain (แนะนำ เร็วที่สุด)

from itertools import chain
from collections import Counter
def highest_freq(lst):
    return Counter(chain.from_iterable(lst)).most_common(1)[0][0]

listA = [[45,20,11],[20,17,45],[20,13,9]]
print(highest_freq(listA))  # 20

สรุป

วิธี 3 ดีที่สุด: O(n) Flatten + Count พร้อมกัน ไม่ต้อง Count ซ้ำ