Python中列表与列表中元组相加问题


>>> second_matrix = [(6, 9), (5, 8), (4, 7)] # 列表中是元组
>>> res =  [1, 2, 3]

# 情况一
>>> res += second_matrix.pop(0)
>>> res
[1, 2, 3, 6, 9]

# 情况二
>>> [1, 2, 3]+(6,9)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "tuple") to list

# 情况三
>>> second_matrix = [(6, 9), (5, 8), (4, 7)]
>>> [1, 2, 3]+second_matrix.pop(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "tuple") to list
>>>


>>> type(second_matrix)
<class 'list'>

情况一不是很理解,难道是因为second_matrix本质还是列表吗?所以列表可以进行运算如果情况一是因为列表,那么情况三也是列表相加减啊

 

求大神赐教!!!

"+"不能用于列表和元组之间,无论谁先谁后。题主代码中的res += second_matrix.pop(0),并非res = res + second_matrix.pop(0),而是等效于:

 res.extend(second_matrix.pop(0))

extend是列表的方法,接受可迭代对象作为参数,比如:

>>> a = [1,2,3]
>>> b = (4,5)
>>> c = 'xyz'
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5]
>>> a.extend(c)
>>> a
[1, 2, 3, 4, 5, 'x', 'y', 'z']

 

type(second_matrix.pop(0))是<class 'tuple'>,type(res)是<class 'list'>,list和tuple直接相加肯定会直接报错,但+=应该有一种往后追加的意思,格式在python里自动就变过来加上了