2014-12-03 54 views
2

我有这样的名单:另一种方法来计算出现在列表中

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

只是算:)

count = 0 
for item in items: 
    if item == 'Boston Americans': 
     count += 1 
print count 
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 
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:使用collection.Counter

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 

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

“我怎么能做到这一点,而不使用计数法” – CoryKramer 2014-12-03 17:55:24

+0

ohhh :)我dident看到我谢谢 – Hackaholic 2014-12-03 17:55:55

+0

或只是collections.Counter?.. – shx2 2014-12-03 18:02:59

2

另一种方式使用sum

sum(x==value for x in mylist) 

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

相关问题