2012-07-01 76 views
0

我正在製作一個示例程序,用於統計字符在給定字中的出現次數。說「好」,g出現一次,o出現2次等等。現在我想通過列表作爲我的字典的值來進一步嘗試,每找到一個現有字符就將第一個元素(索引0)增加1並在單詞 的字符索引中附加相同的字典值列表,例如Word =「Programming is nature」 Dict = {'a':[2,5,16],'i':[2,8,12] ... etc}添加字典列表的值

因此,每個字典的第一個索引值通過一個字符的出現而增加(即,如果找到該字符,則爲+1),但列表中的其他值被附加(保持該字符在該單詞中被找到的位置)。我有這個單獨而不是計算的索引

def count(word): 
    v=0;b={} 
    b.clear() 
    while word[v] in word: 
     if word[v] in b.keys(): 
      b[word[v]]+=1;v+=1 
     else: 
      b[word[v]]=1;v+=1 
     if v==(len(word)): 
      break 
    print("\n",b) 


word=input("Enter word: ") 
count(word) 

回答

2

使用collections.defaultdict代替:

import collections 

def count(word): 
    c = collections.defaultdict(list) 
    for index, letter in enumerate(word): 
     c[letter] += [index] 
    return c 

print count('programming is nature') 

輸出:

defaultdict(<type 'list'>, {'a': [5, 16], ' ': [11, 14], 'e': [20], 'g': [3, 10], 'i': [8, 12], 'm': [6, 7], 'o': [2], 'n': [9, 15], 'p': [0], 's': [13], 'r': [1, 4, 19], 'u': [18], 't': [17]}) 
0

這裏是我的解決辦法:

def count(word): 
    b={} 
    for i,letter in enumerate(word): 
     if letter not in b: 
      b[letter]=[0] 
     b[letter][0]+=1 
     b[letter].append(i) 
return b 

print(c 'mount(「編程性」))

字=「編程性」 打印(數(字))

工作正是你想要的方式。 :)

輸出:

{'a': [2, 5, 16], ' ': [2, 11, 14], 'e': [1, 20], 'g': [2, 3, 10], 'i': [2, 8, 12], 'm': [2, 6, 7], 'o': [1, 2], 'n': [2, 9, 15], 'P': [1, 0], 's': [1, 13], 'r': [3, 1, 4, 19], 'u': [1, 18], 't': [1, 17]} 
0

好了,一些注意事項第一。

您應該使用raw_input而不是input; input評估你作爲Python代碼輸入的內容,raw_input從stdin獲得輸入(如果你使用的是Python 3,則忽略它)。 如果你有一個特定的默認值,你的字典值可以用,collections.defaultdict是非常有用的。

from collections import defaultdict 

def count(word): 
    counts = defaultdict(int) 
    appearances = defaultdict(list) 
    for pos, val in enumerate(word) 
     counts[val] += 1 
     appearances[c].append(pos) 

    print 'counts:', counts 
    print 'appearances:', appearances 

word = input("Enter word: ") 
count(word) 

defaultdict需要調用作爲參數,所以,如果你這樣做:

x = defaultdict(int) 
x['b'] += 1 

因爲'b'是不是X中的一個關鍵,它它初始化的int()值(這是零)。

+2

由OP的使用來看'print()'和'input()'他可以使用Python 3,其中'raw_input'不存在。 –

0

如果您對Python的2.7+,使用Counter

>>> from collections import Counter 
>>> Counter('abchfdhbah') 
Counter({'h': 3, 'a': 2, 'b': 2, 'c': 1, 'd': 1, 'f': 1}) 
>>> the_count = Counter('abchfdhbah') 
>>> the_count['h'] 
3 
0

使用defaultdict有點不同:

from collections import defaultdict 
example = 'Programming is nature' 
D=defaultdict(lambda: [0]) 
for i,c in enumerate(example): 
    D[c][0] += 1 
    D[c].append(i) 
for k,v in D.items(): 
    print(k,v) 

輸出匹配您的例子:

a [2, 5, 16] 
    [2, 11, 14] 
e [1, 20] 
g [2, 3, 10] 
i [2, 8, 12] 
m [2, 6, 7] 
o [1, 2] 
n [2, 9, 15] 
P [1, 0] 
s [1, 13] 
r [3, 1, 4, 19] 
u [1, 18] 
t [1, 17]