2012-10-01 27 views
0

可能重複:
how to get the number of occurrences of each character using pythonPython:沒有。字符串中的每個字符的出現次數的

什麼是獲得一個字符串的每個字符的數量和存儲它的最佳方式(我使用一本字典 - 這種選擇會有很大的不同嗎?)?我想到了幾個方法:

1.

for character in string: 
    if character in characterCountsDict: 
     characterCountsDict[character] += 1 
    else: 
     characterCountsDict[character] = 1 

2.

character = 0 
while character < 127: 
    characterCountsDict[str(unichr(character))] = string.count(str(unichr(character)) 
    character += 1 

我認爲第二種方法比較好... 但要麼是他們的好? 有沒有更好的方法來做到這一點?

回答

2

如果你有興趣的最有效的方式,它似乎是這樣的:

from collections import defaultdict 

def count_chars(s): 
    res = defaultdict(int) 
    for char in s: 
     res[char] += 1 
    return res 

時序:

from collections import Counter, defaultdict 

def test_counter(s): 
    return Counter(s) 

def test_get(s): 
    res = {} 
    for char in s: 
     res[char] = res.get(char, 0) + 1 
    return res 

def test_in(s): 
    res = {} 
    for char in s: 
     if char in res: 
      res[char] += 1 
     else: 
      res[char] = 1 
    return res 

def test_defaultdict(s): 
    res = defaultdict(int) 
    for char in s: 
     res[char] += 1 
    return res 


s = open('/usr/share/dict/words').read() 
#eof 

import timeit 

test = lambda f: timeit.timeit(f + '(s)', setup, number=10) 
setup = open(__file__).read().split("#eof")[0] 
results = ['%.4f %s' % (test(f), f) for f in dir() if f.startswith('test_')] 
print '\n'.join(sorted(results)) 

結果:

0.8053 test_defaultdict 
1.3628 test_in 
1.6773 test_get 
2.3877 test_counter 
+0

謝謝:)絕對過度的答案:) –

+1

@JayanthKoushik:;),想知道我很久以來...這就是爲什麼。 – georg

+0

哇,我不能相信計數器表現如此糟糕,因爲計數器是一個字典 – wim

10
>>> from collections import Counter 
>>> Counter("asdasdff") 
Counter({'a': 2, 's': 2, 'd': 2, 'f': 2}) 

注意,您可以使用Counter的物體,像字典。

+0

真棒!謝謝:) –

+0

哦,等待....對於20MB的字符串,它實際上比方法2(12秒)需要更多時間(30秒)? –

+0

你生成一個類似''asdasd「* 200'的輸入字符串,對吧? – defuz

相關問題