字符串列表的总和引发TypeError

Ell*_*sky 3 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'
Run Code Online (Sandbox Code Playgroud)

Jar*_*uen 9

sum函数采用第二个参数 - 初始累加器值.如果没有提供,则假定为0.因此,您的第一个添加sum(a)0 + '0',产生有问题的类型错误.

相反,你想要:

a = ['0', 'a']
print(''.join(a)) # '0a'
Run Code Online (Sandbox Code Playgroud)

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

  • 如果你要求字符串求和,你应该使用`''.join(a)`,如[**`sum`**]的文档中所述(https://docs.python.org/2/library/ functions.html#总和). (3认同)