How do I solve the "TypeError: can only concatenate str (not "int") to str"

How do I solve the "TypeError: can only concatenate str (not "int") to str"

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

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

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}

将第 10 行更改为

counts[name] = counts[name]+1

即使您遇到的唯一问题是 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))