30秒学会 Python 片段 · 2024年1月15日

30秒学会 Python 片段 – Count occurrences

Counts the occurrences of a value in a list.

  • Use list.count() to count the number of occurrences of val in lst.

代码实现

def count_occurrences(lst, val):
  return lst.count(val)

使用样例

count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3

翻译自:https://www.30secondsofcode.org/python/s/count-occurrences