Python:使用列表切片作为for循环的目标 [英] python: using list slice as target of a for loop

查看:151
本文介绍了Python:使用列表切片作为for循环的目标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现此代码段非常有趣.

I found this code snippet to be very interesting.

a = [0, 1, 2, 3]

for a[-1] in a:
    print(a)

输出如下:

[0, 1, 2, 0]
[0, 1, 2, 1]
[0, 1, 2, 2]
[0, 1, 2, 2]

我试图了解python为什么这样做.是因为python试图重用索引吗? For循环会以某种方式对列表进行切片?

I am trying to understand why python does that. Is it because python is trying to re-use the index? For loop somehow slices the list?

我们可以在迭代列表时添加或删除元素,但是当我们尝试使用索引访问变量时,它会给出奇怪的输出.

We can add or delete an element while iterating the list, but when we are trying to access the variable using index, it gives bizarre output.

有人可以帮助我了解列表中for循环和索引之间的交互吗?还是简单解释一下此输出?

Can someone help me understand the interaction between for loop and index in the list? Or simply explain this output?

推荐答案

它按预期工作. (至少对于预期"有一些解释.)

It works as expected. (For some interpretation of "expected", at least.)

为此重新编写代码,以防止在任何时候误解a[-1]的含义:

Re-writing your code to this, to prevent any misinterpretation of what a[-1] is at any point:

a = [a for a in range(0,4)]
for b in a:
    print (b)
    a[-1] = b
    print (a)

向我们展示

0
[0, 1, 2, 0]
1
[0, 1, 2, 1]
2
[0, 1, 2, 2]
2
[0, 1, 2, 2]

可以清楚地看到将b 赋值分配给a[-1]是立即完成的,并在迭代时更改了列表.

which makes it clear that the b assignment to a[-1] is done immediately, changing the list while iterating.

四个循环执行以下操作:

The four loops do the following:

  1. a[-1]被设置为列表的第一个值0.现在的结果是[0,1,2,0].
  2. a[-1]被设置为第二个值1.结果(很明显)是[0,1,2,1].
  3. a[-1]设置为2,因此结果为[0,1,2,2]-同样,只有a[-1]被更改.
  4. 最后,a[-1]设置为a中的最后一个值,因此有效地它不会改变,最终结果是[0,1,2,2].
  1. a[-1] gets set to the first value of the list, 0. The result is now [0,1,2,0].
  2. a[-1] gets set to the second value, 1. The result is (quite obviously) [0,1,2,1].
  3. a[-1] gets set to 2 and so the result is [0,1,2,2] – again, only a[-1] gets changed.
  4. Finally, a[-1] gets set to the last value in a, so effectively it does not change and the final result is [0,1,2,2].

这篇关于Python:使用列表切片作为for循环的目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆