繁体   English   中英

附加dict列表的值

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM