2013-11-23 93 views

回答

3

count()方法計算的次數的對象在列表中顯示:

a = [5,6,7,2,4,8,5,2,3] 
print a.count(5) # prints 2 

但是,如果你有興趣在總列表中的每一個對象,你可以使用下面的代碼:

counts = {} 
for n in a: 
    total = counts.get(n, 0) 
    counts[n] = counts.get(n, 0) + 1 
print counts 
6

您可以使用collections.Counter

>>> from collections import Counter 
>>> Counter([5,6,7,2,4,8,5,2,3]) 
Counter({2: 2, 5: 2, 3: 1, 4: 1, 6: 1, 7: 1, 8: 1} 
相關問題