列表 + 元组:

1 >>> a = [1, 2]
2 >>> b = (3, 4)
3 >>> a = a + b
4 Traceback (most recent call last):
5   File "<stdin>", line 1, in <module>
6 TypeError: can only concatenate list (not "tuple") to list

列表 += 元组:

1 >>> a += b
2 >>> a
3 [1, 2, 3, 4]

原因:‘ += ’是调用 iadd()函数,然后调用extend函数,extend函数会遍历序列元素再依次加入:

def __iadd__(self, values):
      self.extend(values)
      return self

def extend(self, values):
    'S.extend(iterable) -- extend sequence by appending elements from the iterable'
    for v in values:
        self.append(v)

append()始终将加入的元素作为整体加入:

1 >>> a
2 [1, 2, 3, 4]
3 >>> a.append((5, 6))
4 >>> a
5 [1, 2, 3, 4, (5, 6)]

 

相关文章:

  • 2021-11-29
  • 2021-08-17
  • 2022-12-23
  • 2021-11-29
  • 2021-09-11
  • 2021-10-31
  • 2022-01-20
  • 2021-05-31
猜你喜欢
  • 2021-06-24
  • 2021-11-29
  • 2021-11-29
  • 2021-07-18
  • 2021-07-04
  • 2021-11-27
  • 2022-12-23
相关资源
相似解决方案