2010-07-03 8 views

Antwort

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

Jede Lösung für Python 2.5? Ich verwende dies mit Google App Engine – demos

+1

Sicher können Sie defaultdict verwenden. Ich werde meine Antwort hinzufügen –

+1

Siehe http://code.activestate.com/recipes/576611/ für eine 2.5-Version von Counter. – sdolan

Verwandte Themen