2010-07-03 99 views

回答

31

Python2.7 +

>>> from collections import Counter 
>>> L=['a','b','a','b'] 
>>> print(Counter(L)) 
Counter({'a': 2, 'b': 2}) 
>>> print(Counter(L).items()) 
dict_items([('a', 2), ('b', 2)]) 

的python2.5/2.6

>>> from collections import defaultdict 
>>> L=['a','b','a','b'] 
>>> d=defaultdict(int) 
>>> for item in L: 
>>>  d[item]+=1 
>>>  
>>> print d 
defaultdict(<type 'int'>, {'a': 2, 'b': 2}) 
>>> print d.items() 
[('a', 2), ('b', 2)] 
+0

用於Python 2.5的任何溶液?我使用Google App Engine – demos 2010-07-03 17:14:20

+1

當然,您可以使用defaultdict。我會添加到我的答案 – 2010-07-03 17:16:05

+1

請參閱http://code.activestate.com/recipes/576611/ 2.5版計數器。 – sdolan 2010-07-03 17:18:04

相關問題