Python错误集锦:TypeError: can only concatenate list (not “tuple”) to list

原文链接:http://www.juzicode.com/archives/3623

错误提示:

list用加号进行连接时提示,TypeError: can only concatenate list (not “tuple”) to list

#juzicode.com; #vx:桔子code
a = [1,2,3]
b = (1,2,3)
c = a + b
print(c)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-16-866c3012f69a> in <module>
      2 a = [1,2,3]
      3 b = (1,2,3)
----> 4 c = a + b
      5 print(c)

TypeError: can only concatenate list (not "tuple") to list

错误原因:

1、list类型和tuple类型的数据不能用+直接相加;

解决方法:

1、将tuple类型的数据转换为list后再使用+连接:

#juzicode.com; #vx:桔子code
a = [1,2,3]
b = (1,2,3)
c = a + list(b)  #将tuple转换为list后再用+连接
print(c)

==========运行结果:
[1, 2, 3, 1, 2, 3]

扩展内容:


关注微信公众号“桔子code”,欢迎在后台留言撩我,我会尽我所能为你答疑解惑。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注