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

Find Most Frequent Element ใน List Python: หาสมาชิกที่ปรากฏบ่อยที่สุด

ได้ลิสต์ หาสมาชิกที่มีความถี่สูงสุด (Mode)

วิธี 1: ใช้ max() กับ set() และ count()

listA = [45, 20, 11, 50, 17, 45, 50, 13, 45]
res = max(set(listA), key=listA.count)
print(res)  # 45

วิธี 2: ใช้ collections.Counter (แนะนำ สำหรับข้อมูลมาก)

from collections import Counter
listA = [45, 20, 11, 50, 17, 45, 50, 13, 45]
res = Counter(listA).most_common(1)[0][0]
print(res)  # 45

วิธี 3: ใช้ statistics.mode() (Python 3.4+)

from statistics import mode
listA = [45, 20, 11, 50, 17, 45, 50, 13, 45]
res = mode(listA)
print(res)  # 45

สรุป

  • วิธี 1: O(n²) ช้า สำหรับลิสต์เล็ก
  • วิธี 2: O(n) เร็ว ให้ข้อมูลเพิ่มเติม (count ทุกตัว)
  • วิธี 3: สั้นที่สุด แต่ Raise Error ถ้ามี Mode หลายค่า (multimodal)