Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

python - 如何计算列表项的出现?(How can I count the occurrences of a list item?)

给定一个项目,我如何计算它在Python列表中的出现次数?

  ask by weakish translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 ,如其他答案中所述。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...