Python3.6中的列表

Dic*_*son 8 python python-2.7 python-3.x

我发现了一个关于列表的"有趣"问题.

list1 = [1, 2, 3]
list1.insert(3, list1)
print(list1)
[1, 2, 3, [...]]
POP = list1.pop()
print(POP)
[1, 2, 3]
list1.extend(['a', 'b', 'c'])
print(POP)
[1, 2, 3, 'a', 'b', 'c']
Run Code Online (Sandbox Code Playgroud)

这些以交互模式显示.当然,我知道"insert"只能在列表中插入一个对象.然而,当我插入list1list1.它表明[...],这是什么意思?而且,POP = list1.pop()不是说pop不能只返回最终对象吗?扩展列表后,最终对象应为'c'.为什么它会返回整体list1但没有[...]

Nic*_*ick 4

当您调用时,您将在索引 3处list1.insert(3, list1)插入引用list1,因此您的列表将变为:

[1, 2, 3, [1, 2, 3, [1, 2, 3, [1, 2, 3, [1, 2, 3, [1, 2, 3, [...
Run Code Online (Sandbox Code Playgroud)

您可以通过执行以下操作来看到这一点:

>>> list1[3]
[1, 2, 3, [...]]
>>> list1[3][3]
[1, 2, 3, [...]]
>>> list1[3][3][3]
[1, 2, 3, [...]]
>>> list1[3][3][3][3]
[1, 2, 3, [...]]
Run Code Online (Sandbox Code Playgroud)

你无限地嵌套list1在它自己之中,这就是你看到的原因[...],因为列表是无限长的。

当您随后调用时,POP = list.pop()您将删除引用,因此再次list1变为[1, 2, 3],并POP成为对 的引用list1

因为是对您调用时POP的引用,您也会更新,因为它们都指向同一个列表list1list1.extend(['a', 'b', 'c'])POP


如果你这样做:

list1 = [1, 2, 3]
list1.insert(3, list1[:])
Run Code Online (Sandbox Code Playgroud)

您正在添加一个副本list1因此将得到:

[1, 2, 3, [1, 2, 3]]
Run Code Online (Sandbox Code Playgroud)

然后调用:

POP = list1.pop()
Run Code Online (Sandbox Code Playgroud)

将参考POP列表

此时正在做:

list1.extend(['a', 'b', 'c'])
print(POP)
Run Code Online (Sandbox Code Playgroud)

将输出:

[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

和:

print(list1)
Run Code Online (Sandbox Code Playgroud)

将输出:

[1, 2, 3, 'a', 'b', 'c']
Run Code Online (Sandbox Code Playgroud)

或者,参考这张粗略的图(并不具有真正的代表性):

在此输入图像描述