请问有人能解释一下以下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]
请问有人能解释一下以下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]
这个循环将访问列表的每个插槽,并将其值放入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)
for (a[a.length-1] of a) console.log(a);
。同样的效果。 - trincot基本上,在每次迭代中,列表中的索引位置值都会被替换。 让我先通过一个简单的例子来回答你的问题。
例子:
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
a[-1]
是数组中的最后一个值,因此您正在逐个将数组中的每个值分配给最后一个值。但是,在迭代到4之前,4已被覆盖。 - mousetail