【问题标题】:How do I solve the "TypeError: can only concatenate str (not "int") to str" [closed]如何解决“TypeError:只能将 str(不是“int”)连接到 str”[关闭]
【发布时间】:2019-08-29 11:12:10
【问题描述】:

我收到一个我无法解决的类型错误

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

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}

【问题讨论】:

  • 错字?:counts[name + 1] vs counts[name] + 1
  • 我没有关注你
  • 您想将1 添加到count[name],而不是添加到name,对吗?这就是为什么我认为你只是记错了。

标签: python dictionary histogram counting names


【解决方案1】:

将第 10 行更改为

counts[name] = counts[name]+1

【讨论】:

  • 非常感谢!
【解决方案2】:

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

【讨论】:

  • 非常感谢!好建议!
  • @Neb967 您应该将您认为有帮助的答案标记为已接受。
猜你喜欢
  • 2018-12-17
  • 2021-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-18
  • 2020-08-19
  • 1970-01-01
相关资源
最近更新 更多