为什么以下会引发 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/