为什么下面提到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'
Tags:
^{} 函数接受第二个参数—初始累加器值。如果没有提供,则假定为0。因此,您的
sum(a)
中的第一个加法是0 + '0'
,产生了所讨论的类型错误。你知道吗相反,您希望:
如果您尝试在字符串上使用
sum
,您将得到一个错误,即改为使用''.join(seq)
。你知道吗相关问题 更多 >
编程相关推荐