Skip to content

Latest commit

 

History

History
25 lines (18 loc) · 733 Bytes

79.md

File metadata and controls

25 lines (18 loc) · 733 Bytes
rank vote view answer url
79 1561 1740379 24 url

如何计算列表中元素出现的个数?


如果你想计算单个元素出现的次数,使用 count 方法:

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

不要在计算多个元素时使用这个方法.每次调用 count 方法都会迭代一边列表,性能会很低,如果你需要计算所有的元素或者指定几个元素可以使用 Counter.

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