为什么以下提出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)
该sum函数采用第二个参数 - 初始累加器值.如果没有提供,则假定为0.因此,您的第一个添加sum(a)是0 + '0',产生有问题的类型错误.
相反,你想要:
a = ['0', 'a']
print(''.join(a)) # '0a'
Run Code Online (Sandbox Code Playgroud)
如果您尝试使用sum字符串,则会收到错误消息,说明要使用它''.join(seq).