我该如何解决“ TypeError:只能将str(而不是“ int”)连接到str”

时间:2019-08-29 11:12:10

标签: python dictionary histogram counting names

我遇到无法解决的类型错误

这是为字典构造一个计数器:

counts = dict()
names = ['csev','cwen', 'csev', 'zqian', 'cwen']

#makes new tally for new names and updates existing names
for name in names :
    if name not in counts:
        counts[name] = 1
    else:
        counts[name] = counts[name + 1]

print(counts)

应输出:

{'csev':2, 'zqian':1, 'cwen':2}

2 个答案:

答案 0 :(得分:0)

将第10行更改为

counts[name] = counts[name]+1

答案 1 :(得分:0)

即使您遇到的唯一问题是counts[name + 1](由于要增加计数而不是名称,所以应该为counts[name] + 1),但您应该考虑使用collections.Counter来完成此任务:

from collections import Counter
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
counts = Counter(names)

尽管Counter是类dict的对象,但是如果您想使用dict对象,请使用:

counts = dict(Counter(names))
相关问题