[英]Appending values of dict list
我正在制作一個示例程序來計算一個字符在給定單詞中出現的次數。 說“好”,g發生一次,o發生2次等等。現在我想嘗試通過將列表作為我的字典的值來進一步增加這一點,每次找到現有字符時將第一個元素(索引0)增加1並通過單詞中的字符索引附加相同的字典值列表,例如Word =“Programming is nature”Dict = {'a':[2,5,16],'i':[2,8, 12] ...等}
因此,每個字典值的第一個索引會因字符的出現而增加(即,如果找到字符,則為+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)
請改為使用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]})
這是我的解決方案:
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
打印(計數(“編程是自然”))
word =“編程是自然”打印(計數(字))
完全按照您希望的方式工作。 :)
輸出:
{'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]}
好的,所以先注意一下。
您應該使用raw_input而不是input ; input
評估您輸入的Python代碼, raw_input
從stdin獲取輸入(如果您使用的是Python 3,請忽略它)。 如果您的dict值可以使用特定的默認值,則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
將callable作為其參數,所以如果你這樣做:
x = defaultdict(int)
x['b'] += 1
因為'b'
不是x中的鍵,所以它將其初始化為int()
的值(為零)。
如果您使用的是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
使用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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.