字符串列表的总和引发TypeError

时间:2017-04-14 20:48:32

标签: 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'

1 个答案:

答案 0 :(得分:9)

sum函数接受第二个参数 - 初始累加器值。如果未提供此选项,则假定为0.因此,sum(a)中的第一个添加内容为0 + '0',从而产生相关类型错误。

相反,你想:

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

如果您尝试在字符串上使用sum,则会收到错误消息,说明要使用''.join(seq)