我遇到无法解决的类型错误
这是为字典构造一个计数器:
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}
答案 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))