Python list.count() 方法用于统计元素出现的次数。
语法
lst.count(value)参数
value:要统计的元素。
返回值
返回元素在列表中出现的次数(整数)。
示例
nums = [1, 2, 3, 1, 1, 4]
print(nums.count(1)) # 3
print(nums.count(5)) # 0
words = ["a", "b", "a", "c", "a"]
print(words.count("a")) # 3
# 找到出现超过1次的值
dup = [x for x in set(nums) if nums.count(x) > 1]
print(dup) # [1]输出:
3
0
3
[1]注意事项
count 查找需遍历整个列表,大列表用 Counter(collections)更高效。