擅长:python、mysql、java
<p>当其他答案(使用list.count)起作用时,它们在大列表上的速度可能会慢得令人望而却步。</p>
<p>考虑使用<code>collections.Counter</code>,如<a href="http://docs.python.org/library/collections.html" rel="noreferrer">http://docs.python.org/library/collections.html</a>中所述</p>
<p>示例:</p>
<pre><code>>>> # Tally occurrences of words in a list
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
... cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})
</code></pre>