30秒学会 Python 片段 · 2019年6月19日

30秒学会 Python 片段 – count_occurences

Counts the occurrences of a value in a list.

Increment a counter for every item in the list that has the given value and is of the same type.

代码实现

def count_occurrences(lst, val):
  return len([x for x in lst if x == val and type(x) == type(val)])

使用样例

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