If you only want one item's count, use the count
method:
(如果您只想要一项的计数,请使用count
方法:)
>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3
Don't use this if you want to count multiple items.
(如果要计数多个项目,请不要使用此选项。)
Calling count
in a loop requires a separate pass over the list for every count
call, which can be catastrophic for performance. (循环调用count
需要为每个count
调用单独遍历列表,这可能会对性能造成灾难性影响。)
If you want to count all items, or even just multiple items, use Counter
, as explained in the other answers. (如果您要计算所有项目,甚至只是多个项目,请使用Counter
,如其他答案中所述。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…