บทนำ
เมื่อมี matrix (list of lists) ที่แต่ละแถวอาจมีความยาวต่างกัน ต้องการนับว่าแต่ละความยาวเกิดขึ้นกี่ครั้ง ใช้ dictionary นับความถี่ (frequency count)
ตัวอย่างโค้ด
my_list = [[42, 24, 11], [67, 18], [20], [54, 10, 25], [45, 99]]
print("Matrix:", my_list)
# นับความถี่ความยาวแถว
freq = {}
for row in my_list:
length = len(row)
if length not in freq:
freq[length] = 1
else:
freq[length] += 1
print("ความถี่ความยาวแถว:", freq)
ผลลัพธ์
Matrix: [[42, 24, 11], [67, 18], [20], [54, 10, 25], [45, 99]]
ความถี่ความยาวแถว: {1: 1, 2: 2, 3: 2}
วิธีที่สั้นกว่าและ Pythonic มากกว่า
1. ใช้ collections.Counter
from collections import Counter
freq = Counter(len(row) for row in my_list)
print(dict(freq)) # {3: 2, 2: 2, 1: 1}
2. ใช้ dict.get()
freq = {}
for row in my_list:
freq[len(row)] = freq.get(len(row), 0) + 1
print(freq)
3. ใช้ defaultdict
from collections import defaultdict
freq = defaultdict(int)
for row in my_list:
freq[len(row)] += 1
print(dict(freq))
การประยุกต์: สถิติเพิ่มเติม
import statistics
lengths = [len(row) for row in my_list]
print(f"ความยาวแถว: {lengths}")
print(f"ค่าเฉลี่ย: {statistics.mean(lengths):.2f}")
print(f"ค่ามัธยฐาน: {statistics.median(lengths)}")
print(f"ค่าที่พบมากที่สุด: {statistics.mode(lengths)}")
print(f"ค่ากระจาย: {statistics.stdev(lengths):.2f}")
กรณีใช้งานจริง
- ตรวจสอบความสม่ำเสมอของข้อมูล (ragged array detection)
- Validate input ก่อนสร้าง NumPy array (ต้อง rectangular)
- วิเคราะห์ log lines, CSV rows ที่มีฟิลด์ไม่ครบ
ขยายเป็น DataFrame
import pandas as pd
df = pd.DataFrame({'row_length': [len(r) for r in my_list]})
print(df['row_length'].value_counts().sort_index())
# 1 1
# 2 2
# 3 2
# Name: row_length, dtype: int64
สรุป
ใช้ Counter(len(row) for row in matrix) สำหรับโค้ดสั้นที่สุดและอ่านง่าย หรือ defaultdict(int) สำหรับการสะสมแบบทบเพิ่ม ทั้งคู่เป็น Pythonic และมีประสิทธิภาพ