2010-07-03 12 views

Odpowiedz

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

Każdy roztwór Pythona 2,5? Używam tego z Google App Engine – demos

+1

Oczywiście, możesz użyć defaultdict. Dodam do mojej odpowiedzi –

+1

Zobacz http://code.activestate.com/recipes/576611/ dla wersji 2.5 Licznika. – sdolan

Powiązane problemy