我遇到了一个无法解决的类型错误
这是为字典构造计数器:
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 + 1]
(应该是counts[name] + 1
,因为您希望增加计数而不是名称),您也应该考虑使用collections.Counter
来执行此任务:虽然
Counter
是一个类似dict
的对象,但是如果您想要一个dict
对象,请使用:相关问题 更多 >
编程相关推荐