另一种计算列表中出现次数的方法

时间:2014-12-03 17:50:55

标签: python list count

我有这个清单:

['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']

说我想计算"Boston Americans"在列表中的次数。

如何在不使用.count方法list.count("Boston Americans")或任何导入的情况下执行此操作?

4 个答案:

答案 0 :(得分:2)

您可以使用内置sum()功能:

>>> 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']
>>> sum(1 for i in l if i=="Boston Americans")
1
>>> sum(1 for i in l if i=='Boston Red Sox')
4

答案 1 :(得分:2)

使用sum的另一种方法:

sum( x==value for x in mylist )

在这里,我们使用事实TrueFalse可以视为整数0和1。

答案 2 :(得分:0)

算一下:)

count = 0
for item in items:
    if item == 'Boston Americans':
        count += 1
print count

答案 3 :(得分:0)

使用filterlambda

>>> a = ['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']
>>> len(filter(lambda x : x=='Boston Americans',a))
1
>>> len(filter(lambda x : x=='Boston Red Sox',a))
4

其他好方法但你需要导入模块

使用itertools.groupby

import itertools
>>> my_count = {x:len(list(y)) for x,y in itertools.groupby(sorted(a))}
>>> my_count['Boston Americans']
1
>>> my_count['Boston Red Sox']
4

使用collection.Counter

>>> from collections import Counter
>>> my_count = Counter(a)
>>> my_count['Boston Americans']
1
>>> my_count['Boston Red Sox']
4