Trong bài viết này, chúng ta phát triển chương trình đếm tần suất xuất hiện của mỗi phần tử trong list.
Cách 1: Dùng Dictionary (Manual counting)
lst = ['a', 'b', 'a', 'c', 'd', 'c', 'c']
frequency = {}
for item in lst:
if item in frequency:
frequency[item] += 1
else:
frequency[item] = 1
for key, value in frequency.items():
print(f"{key} -> {value}")
Kết quả
a -> 2 b -> 1 c -> 3 d -> 1
Cách 2: Dùng list.count()
lst = ['a', 'b', 'a', 'c', 'd', 'c', 'c']
frequency = {}
for item in lst:
frequency[item] = lst.count(item)
for key, value in frequency.items():
print(f"{key} -> {value}")
Kết quả
a -> 2 b -> 1 c -> 3 d -> 1
Cách 3: collections.Counter (Khuyến nghị - Pythonic nhất)
from collections import Counter
lst = ['a', 'b', 'a', 'c', 'd', 'c', 'c']
frequency = Counter(lst)
print(frequency) # Counter({'c': 3, 'a': 2, 'b': 1, 'd': 1})
for key, value in frequency.items():
print(f"{key} -> {value}")
So sánh hiệu năng
- Dictionary manual: O(n) - tốt
count()trong loop: O(n²) - chậm với list lớnCounter: O(n), code ngắn, nhiều method hữu ích (most_common(),elements())
Khuyến nghị: Dùng collections.Counter cho mọi trường hợp thực tế.