python - 字符串列表的总和引发 TypeError

标签 python python-3.5

为什么以下会引发 TypeError?我的列表是同类型的!

>>> a
['0', 'a']
>>> type(a[0])
<class 'str'>
>>> type(a[1])
<class 'str'>
>>> sum(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

最佳答案

sum函数采用第二个参数 - 初始累加器值。如果未提供,则假定为 0。因此,sum(a) 中的第一个加法是 0 + '0',从而产生类型错误问题。

相反,你想要:

a = ['0', 'a']
print(''.join(a)) # '0a'

如果您尝试对字符串使用 sum,您将收到一条错误消息,提示您改为使用 ''.join(seq)

关于python - 字符串列表的总和引发 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43419037/

相关文章:

Python "requests"在线程中不工作/阻塞?

python - Daphne,安装 django channel 时出现扭曲的 pip 错误

random - 在 python 3.5 中使用 random.choices() 的替代方法是什么

python - git log 漂亮格式可以保留主题中的新行吗?

python - Pandas/SQLalchemy 合并数据框和表

python - Selenium python无法向下滚动

python - 形状文件输出

json - django jsonresponse 中的特殊字符 (utf-8)

python - 如何在 mypy 中定义隐含导入?

Python 3.5 与 3.6 相比,是什么让 "map"比理解更慢