列表方法append()和extend()之间有什么区别?


当前回答

append(object)通过将对象添加到列表来更新列表。

x = [20]
# List passed to the append(object) method is treated as a single object.
x.append([21, 22, 23])
# Hence the resultant list length will be 2
print(x)
--> [20, [21, 22, 23]]

extend(list)本质上连接两个列表。

x = [20]
# The parameter passed to extend(list) method is treated as a list.
# Eventually it is two lists being concatenated.
x.extend([21, 22, 23])
# Here the resultant list's length is 4
print(x)
--> [20, 21, 22, 23]

其他回答

append附加一个元素。extend附加元素列表。

请注意,如果您传递一个列表进行追加,它仍然会添加一个元素:

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

append(object)通过将对象添加到列表来更新列表。

x = [20]
# List passed to the append(object) method is treated as a single object.
x.append([21, 22, 23])
# Hence the resultant list length will be 2
print(x)
--> [20, [21, 22, 23]]

extend(list)本质上连接两个列表。

x = [20]
# The parameter passed to extend(list) method is treated as a list.
# Eventually it is two lists being concatenated.
x.extend([21, 22, 23])
# Here the resultant list's length is 4
print(x)
--> [20, 21, 22, 23]

append将元素添加到列表中。extend将第一个列表与另一个列表/可迭代列表连接起来。

>>> xs = ['A', 'B']
>>> xs
['A', 'B']

>>> xs.append("D")
>>> xs
['A', 'B', 'D']

>>> xs.append(["E", "F"])
>>> xs
['A', 'B', 'D', ['E', 'F']]

>>> xs.insert(2, "C")
>>> xs
['A', 'B', 'C', 'D', ['E', 'F']]

>>> xs.extend(["G", "H"])
>>> xs
['A', 'B', 'C', 'D', ['E', 'F'], 'G', 'H']

append在列表末尾附加指定的对象:

>>> x = [1, 2, 3]
>>> x.append([4, 5])
>>> print(x)
[1, 2, 3, [4, 5]]

extend通过从指定的iterable中附加元素来扩展列表:

>>> x = [1, 2, 3]
>>> x.extend([4, 5])
>>> print(x)
[1, 2, 3, 4, 5]

追加“扩展”列表(在适当位置)仅一个项,传递单个对象(作为参数)。

extend将列表(就地)扩展到传递的对象(作为参数)所包含的项目。

对于str对象,这可能会有点混淆。

如果将字符串作为参数传递:append将在末尾添加一个字符串项,但extend将添加与该字符串长度相同的“单个”str项。如果将字符串列表作为参数传递:append仍将在末尾添加单个“列表”项,并且extend将添加与传递列表长度相同的“列表”项。

def append_o(a_list,元素):a_list.append(元素)打印('append:',end='')对于a_list中的项目:打印(项,结束=',')打印()def extend_o(a_list,元素):a_list.exextend(元素)打印('extend:',end='')对于a_list中的项目:打印(项,结束=',')打印()append_o(['ab'],'cd')扩展_ o([‘ab’],‘d’)append_o(['ab'],['cd','ef'])extend_o(['ab'],['cd','ef'])附加(['ab'],['cd'])扩展_ o([‘ab’],[‘cd’])

生产:

append: ab,cd,
extend: ab,c,d,
append: ab,['cd', 'ef'],
extend: ab,cd,ef,
append: ab,['cd'],
extend: ab,cd,