假设我的代码如下:
Numbers = [1, 2, 3, 4]
Print(Numbers.count(1,2))
如何让输出返回 2?
最佳答案
sum(map(Numbers.count, (1,2)))
一旦要计算的元素数量增加,最好使用 collections.Counter
并从那里添加计数:
from collections import Counter
c = Counter(Numbers)
sum(c[x] for x in (1,2))
后一种方法的主要优点是 Counter
在单次迭代中获得所有计数,而重复的 list.count
调用重复迭代列表。
关于python - 使用 list.count 搜索列表中的多个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51403730/