在Python中使用索引作为for循环变量

5

请问有人能解释一下以下Python代码吗?

a = [1, 2, 3, 4]
for a[-1] in a:
    print(a)

执行后,我得到了以下结果,但我无法理解背后的整个逻辑。

结果

[1, 2, 3, 1]
[1, 2, 3, 2]
[1, 2, 3, 3]
[1, 2, 3, 3]

1
a[-1] 是数组中的最后一个值,因此您正在逐个将数组中的每个值分配给最后一个值。但是,在迭代到4之前,4已被覆盖。 - mousetail
你好奇这段代码是从哪里找到的? - GordonAitchJay
2个回答

2

这个循环将访问列表的每个插槽,并将其值放入a[-1],即列表的最后一个插槽。在这种情况下,a[-1]是对与a[3]相同插槽的引用。

因此,我们可以将循环展开为:

a = [1, 2, 3, 4]
a[3] = a[0]  # First iteration
print(a)
a[3] = a[1]  # Second iteration
print(a)
a[3] = a[2]  # Third iteration
print(a)
a[3] = a[3]  # Last iteration. Nothing changes here
print(a)

所以in关键字可以在列表中进行赋值?感觉很奇怪。 - BurnNote
1
当然,这不是一个好的程序员会做的事情,我想这只是一个虚构的练习。但它并不特定于Python。例如,在JavaScript中,它将是 for (a[a.length-1] of a) console.log(a);。同样的效果。 - trincot
这是一致的行为,in 的整个目的是用于赋值。保持赋值的一般规则也是有意义的。但这仍然是一个我没有想到的组合。从这个角度来看,这是一个非常好的问题。 - BurnNote

1

基本上,在每次迭代中,列表中的索引位置值都会被替换。 让我先通过一个简单的例子来回答你的问题。

例子:

a = [1, 2, 3, 4]
for a[0] in a:
    print(a[0])
    print(a)   # It replaces the first position a[0] with each iteration a[0, 1, 2, 3]

输出:

1              => (iteration 1, a[0]=1, replaced with 1 in a[0] position)
[1, 2, 3, 4]
2              => (iteration 2, a[0]=2, replaced with 2 in a[0] position)
[2, 2, 3, 4]
3              => (iteration 3, a[0]=3, replaced with 3 in a[0] position)
[3, 2, 3, 4]
4
[4, 2, 3, 4]   => (iteration 4, a[0]=4, replaced with 4 in a[0] position)

您查询的解释:

a = [1, 2, 3, 4]
for a[-1] in a:
    print(a[-1])
    print(a)   # It replaces the last position a[-1] with each iteration a[0, 1 ,2, 3]

输出:

1               => (iteration 1, a[-1]=1, replaced with 1 in a[-1] position)
[1, 2, 3, 1]
2               => (iteration 2, a[-1]=2, replaced with 2 in a[-1] position)
[1, 2, 3, 2]
3               => (iteration 3, a[-1]=3, replaced with 3 in a[-1] position)
[1, 2, 3, 3]
3               => (iteration 4, a[-1]=3 (as the position is already 
[1, 2, 3, 3]        replaced with 3. So, placed with 3 in a[-1] position))


非常出色的演示,特别是最后一次迭代中将最后一个元素改为 3 而不是原来的 4,在您解释之前有些令人困惑。 - hc_dev

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