我发现这段代码片段非常有趣.
a = [0, 1, 2, 3]
for a[-1] in a:
print(a)
Run Code Online (Sandbox Code Playgroud)
输出如下:
[0, 1, 2, 0]
[0, 1, 2, 1]
[0, 1, 2, 2]
[0, 1, 2, 2]
Run Code Online (Sandbox Code Playgroud)
我试图理解为什么python会这样做.是因为python试图重用索引吗?for循环以某种方式切片列表?
我们可以在迭代列表时添加或删除元素,但是当我们尝试使用索引访问变量时,它会产生奇怪的输出.
有人可以帮我理解列表中for循环和索引之间的交互吗?或者只是解释这个输出?