Python中的列表操作中,plus和append有什么区别?

18
5个回答

26

有两个主要的区别。第一个区别是+更接近于extend而非append

>>> a = [1, 2, 3]
>>> a + 4
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    a + 4
TypeError: can only concatenate list (not "int") to list
>>> a + [4]
[1, 2, 3, 4]
>>> a.append([4])
>>> a
[1, 2, 3, [4]]
>>> a.extend([4])
>>> a
[1, 2, 3, [4], 4]

另一个更显著的区别是这些方法会在原地进行操作:extend实际上就像 += - 实际上,它与 += 的行为完全相同,只是它可以接受任何可迭代对象,而 += 只能接受另一个列表。


在2019年的Python3中,这仍然准确吗? - Scott Skiles
+= can only take another list.I think it can take tuples too or else how do explain being able to add to a list with += 8, - mj_codec

22

使用 list.append 直接修改列表 - 它的结果是 None。使用 + 创建一个新的列表。


1
+1,这很重要,因为列表是可变的。使用 + 操作符可以创建一个新的列表,而不改变原始列表,你应该知道你是否打算改变原始列表。 - Azim

4
>>> L1 = [1,2,3]
>>> L2 = [97,98,99]
>>>
>>> # Mutate L1 by appending more values:
>>> L1.append(4)
>>> L1
[1, 2, 3, 4]
>>>
>>> # Create a new list by adding L1 and L2 together
>>> L1 + L2
[1, 2, 3, 4, 97, 98, 99]
>>> # L1 and L2 are unchanged
>>> L1
[1, 2, 3, 4]
>>> L2
[97, 98, 99]
>>>
>>> # Mutate L2 by adding new values to it:
>>> L2 += [999]
>>> L2
[97, 98, 99, 999]

1

+ 是一个二元运算符,它将两个操作数列表连接起来并生成一个新的列表。 append 是一个实例方法,它将单个元素附加到现有列表中。

P.S. 你是不是想用 extend


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接