文章内容

2021/4/23 18:21:48,作 者: 黄兵

Python 计算某个数字在列表中出现的次数

以下是在Python中计算某个数字在列表中出现的次数:

>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3

如果您要计算多个项目,请不要使用它。count循环调用需要为每个count调用单独遍历列表,这可能会对性能造成灾难性的影响。如果您要计算所有项目,甚至只是多个项目,请使用Counter

下面是Counter的示例:

>>> from collections import Counter
>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> Counter(z)
Counter({'blue': 3, 'red': 2, 'yellow': 1})

关于这两个函数的比较,可以参考下面的参考资料。


参考资料:

1、How can I count the occurrences of a list item?

分享到:

发表评论

评论列表