为什么以下内容会引发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'
答案 0 :(得分:9)
sum
函数接受第二个参数 - 初始累加器值。如果未提供此选项,则假定为0.因此,sum(a)
中的第一个添加内容为0 + '0'
,从而产生相关类型错误。
相反,你想:
a = ['0', 'a']
print(''.join(a)) # '0a'
如果您尝试在字符串上使用sum
,则会收到错误消息,说明要使用''.join(seq)
。