Skip to main content
 首页 » 编程设计

python之使用 list.count 搜索列表中的多个项目

2025年05月04日11qq号

假设我的代码如下:

Numbers = [1, 2, 3, 4] 
 
Print(Numbers.count(1,2)) 

如何让输出返回 2?

请您参考如下方法:

最简单的方法,使用 sum和 map :

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 调用重复迭代列表。