字符串列表的总和

2024-06-11 10:12:25 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么下面提到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: mosttypestdinlinecallclassfilelast
1条回答
网友
1楼 · 发布于 2024-06-11 10:12:25

^{}函数接受第二个参数—初始累加器值。如果没有提供,则假定为0。因此,您的sum(a)中的第一个加法是0 + '0',产生了所讨论的类型错误。你知道吗

相反,您希望:

a = ['0', 'a']
print(''.join(a)) # '0a'

如果您尝试在字符串上使用sum,您将得到一个错误,即改为使用''.join(seq)。你知道吗

相关问题 更多 >