<p>要计算列表中每个条目的数量,可以使用<code>collections</code>模块中的<code>Counter</code>类:</p>
<pre><code>l =['Boston Americans', 'New York Giants', 'Chicago White Sox', 'Chicago Cubs', 'Chicago Cubs', 'Pittsburgh Pirates', 'Philadelphia Athletics', 'Philadelphia Athletics', 'Boston Red Sox', 'Philadelphia Athletics', 'Boston Braves', 'Boston Red Sox', 'Boston Red Sox', 'Chicago White Sox', 'Boston Red Sox', 'Cincinnati Reds', 'Cleveland Indians', 'New York Giants', 'New York Giants', 'New York Yankees', 'Washington Senators', 'Pittsburgh Pirates', 'St. Louis Cardinals', 'New York Yankees', 'New York Yankees', 'Philadelphia Athletics', 'Philadelphia Athletics', 'St. Louis Cardinals', 'New York Yankees', 'New York Giants', 'St. Louis Cardinals', 'Detroit Tigers', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'New York Yankees', 'Cincinnati Reds', 'New York Yankees', 'St. Louis Cardinals', 'New York Yankees', 'St. Louis Cardinals', 'Detroit Tigers', 'St. Louis Cardinals', 'New York Yankees', 'Cleveland Indians', 'New York Yankees', 'New York Yankees']
from collections import Counter
c = Counter(l)
print(c)
</code></pre>
<p><code>c</code>是一个<code>Counter</code>对象,它保存每个不同条目/键在列表中出现的次数。由于<code>Counter</code>是从<code>dict</code>派生的,所以您可以像访问任何其他字典一样访问它。</p>
<pre><code>Counter({'New York Yankees': 13, 'St. Louis Cardinals': 6, 'Philadelphia Athletics': 5, 'New York Giants': 4, 'Boston Red Sox': 4, 'Chicago White Sox': 2, 'Pittsburgh Pirates': 2, 'Detroit Tigers': 2, 'Cincinnati Reds': 2, 'Cleveland Indians': 2, 'Chicago Cubs': 2, 'Boston Americans': 1, 'Boston Braves': 1, 'Washington Senators': 1})
</code></pre>