我有这个清单:
['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")
或任何导入的情况下执行此操作?
答案 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 )
在这里,我们使用事实True
和False
可以视为整数0和1。
答案 2 :(得分:0)
算一下:)
count = 0
for item in items:
if item == 'Boston Americans':
count += 1
print count
答案 3 :(得分:0)
使用filter
和lambda
:
>>> 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