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

นับความถี่ของทุกองค์ประกอบในอาร์เรย์ด้วย Python

มีหลายวิธีในการนับความถี่ (frequency) ของแต่ละค่าในลิสต์ นี่คือ 2 วิธีที่นิยมใช้

วิธีที่ 1: ใช้ Dictionary (dict)

arr = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]
elements_count = {}

for element in arr:
    if element in elements_count:
        elements_count[element] += 1
    else:
        elements_count[element] = 1

for key, value in elements_count.items():
    print(f"{key}: {value}")

ผลลัพธ์

1: 3
2: 4
3: 5

วิธีที่ 2: ใช้ collections.Counter (แนะนำ)

import collections

arr = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]
elements_count = collections.Counter(arr)

for key, value in elements_count.items():
    print(f"{key}: {value}")

ผลลัพธ์

1: 3
2: 4
3: 5

เปรียบเทียบ

วิธีความสะดวกประสิทธิภาพ
dict แบบ manualเข้าใจง่าย สำหรับมือใหม่ดี
Counterสั้น กระชับ มาตรฐานดีเยี่ยม (optimized)

สรุป

ควรใช้ collections.Counter สำหรับงานจริง เพราะเขียนน้อยกว่าและเร็วกว่า