2012-12-10 46 views

回答

9
In [27]: mystr = "aaabbc" 

In [28]: collections.Counter(mystr) 
Out[28]: Counter({'a': 3, 'b': 2, 'c': 1}) 

In [29]: dict(collections.Counter(mystr)) 
Out[29]: {'a': 3, 'b': 2, 'c': 1} 
+1

值得注意的計數器進來2.7 + –

1
from collections import defaultdict 

d = defaultdict(int) 

for ltr in my_string: 
    d[ltr] += 1 

print d 

這個已經被問了幾次才......

這裏是在Python 2.7 <

+1

只要OP沒有被一個古老的python2.4卡住:-p – mgilson

+0

好點先生:) –

0

工程,並使用正則表達式的答案,你是不是僅限於一個單一的字符,但:

import re 
p = re.compile("a") 
len(p.findall("aaaaabc")) //5 

如果你想了解更多,請訪問這裏:http://docs.python.org/2/howto/regex.html

+0

這幾乎肯定不是「正確」的方式來做到這一點(即使它的工作原理) –

+0

如果他需要計數多於一個字符,或者更好的複雜模式,它其實是非常正確的。 OP沒有真正描述他需要這樣做,所以我只是讓他知道一個可擴展的做事方式。 – corazza

1

考慮您還想0返回不在字符串中的元素,你可以試試這個:

def AnotherCounter (my_string, *args): 
    my_dict = {ele : 0 for ele in args} 
    for s in my_string: 
     my_dict[s] +=1 
    return my_dict 

結果:

>>> AnotherCounter("aaabbc", 'a', 'b', 'c', 'd') 
{'a': 3, 'c': 1, 'b': 2, 'd': 0} 
相關問題