Python count() - List 計數

count() 方法用來計算元素在 list 中出現的次數。

基本用法

numbers = [1, 2, 3, 2, 4, 2, 5]
count = numbers.count(2)
print(count)  # 3

語法

list.count(element)
  • element:要計算的元素
  • 回傳:元素出現的次數

元素不存在時回傳 0

numbers = [1, 2, 3]
print(numbers.count(5))  # 0

不同類型的元素

mixed = [1, "hello", 1.0, True, "hello", None, True]

print(mixed.count(1))        # 2(1 和 True 相等)
print(mixed.count("hello"))  # 2
print(mixed.count(None))     # 1
print(mixed.count(True))     # 2(True 和 1 相等)
Python 中 True == 1False == 0,所以計數時會被視為相等。

字串的 count()

字串也有 count() 方法:

text = "hello world"
print(text.count("o"))     # 2
print(text.count("ll"))    # 1
print(text.count("world")) # 1

實際範例

統計投票結果

votes = ["A", "B", "A", "C", "A", "B", "A", "C", "B"]

candidates = set(votes)
results = {c: votes.count(c) for c in candidates}
print(results)  # {'A': 4, 'B': 3, 'C': 2}

# 找出獲勝者
winner = max(results, key=results.get)
print(f"Winner: {winner}")  # Winner: A

找出出現最多次的元素

def most_common(lst):
    if not lst:
        return None
    return max(set(lst), key=lst.count)

numbers = [1, 2, 3, 2, 4, 2, 5, 3, 3]
print(most_common(numbers))  # 2 或 3(都出現 3 次)

使用 Counter(更高效)

from collections import Counter

numbers = [1, 2, 3, 2, 4, 2, 5, 3, 3]

# 計算所有元素的出現次數
counter = Counter(numbers)
print(counter)  # Counter({2: 3, 3: 3, 1: 1, 4: 1, 5: 1})

# 找出最常見的元素
print(counter.most_common(1))  # [(2, 3)] 或 [(3, 3)]
print(counter.most_common(2))  # [(2, 3), (3, 3)]

檢查重複

def has_duplicates(lst):
    for item in set(lst):
        if lst.count(item) > 1:
            return True
    return False

# 更高效的方法
def has_duplicates(lst):
    return len(lst) != len(set(lst))

print(has_duplicates([1, 2, 3, 4]))     # False
print(has_duplicates([1, 2, 3, 2, 4]))  # True

找出所有重複的元素

def find_duplicates(lst):
    return [item for item in set(lst) if lst.count(item) > 1]

numbers = [1, 2, 3, 2, 4, 3, 5]
print(find_duplicates(numbers))  # [2, 3]

統計字元頻率

text = "hello world"
chars = list(text.replace(" ", ""))

frequency = {c: chars.count(c) for c in set(chars)}
print(frequency)
# {'h': 1, 'e': 1, 'l': 3, 'o': 2, 'w': 1, 'r': 1, 'd': 1}

分組統計

students = [
    {"name": "Alice", "grade": "A"},
    {"name": "Bob", "grade": "B"},
    {"name": "Charlie", "grade": "A"},
    {"name": "David", "grade": "C"},
    {"name": "Eve", "grade": "B"},
]

grades = [s["grade"] for s in students]
grade_counts = {g: grades.count(g) for g in set(grades)}
print(grade_counts)  # {'A': 2, 'B': 2, 'C': 1}

效能考量

count() 的時間複雜度是 O(n)。如果需要計算多個元素的出現次數,使用 Counter 更高效:

from collections import Counter

numbers = [1, 2, 3, 2, 4, 2, 5, 3, 3]

# 低效:對每個元素呼叫 count(),O(n²)
for num in set(numbers):
    print(f"{num}: {numbers.count(num)}")

# 高效:使用 Counter,O(n)
counter = Counter(numbers)
for num, count in counter.items():
    print(f"{num}: {count}")