2014-12-03 58 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.

相關問題