มีหลายวิธีในการนับความถี่ (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 สำหรับงานจริง เพราะเขียนน้อยกว่าและเร็วกว่า