循环和遍历列表 [英] for loops and iterating through lists
问题描述
下面是一段代码,它给出了输出: 0 1 2 2
。因为 a [-1]
访问列表中的数字3,所以我期望输出 3 3 3 3
。网上给出的解释是:每次迭代中 a [-1]
的值发生变化,但我不太明白如何或为什么。任何解释都会很棒!
pre $ code a = [0,1,2,3]
for a [-1 ] in a:
print(a [-1])$ b $ b
这里发生了什么是一个列表在循环过程中发生了变化。
让我们考虑下面的代码片段:
a = [0, 1,2,3]
为a:
中的[-1]打印
输出是:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ ,1]
[0,1,2,2]
[0,1,2,2]
每次迭代:
- 从内部指针当前指向的位置读取值
- 最后一个元素打印在标准输出中b
所以它是这样的:
- 内部指针指向第一个元素,它是0,最后一个元素被该值覆盖;列表是
[0,1,2,0]
;打印的值是0
- 内部指针指向第二个元素,它是1,最后一个元素被该值覆盖;清单是
[0,1,2,1]
;打印的值在最后一步是1
- (...)
- 指向最后一个元素;最后一个元素被自己覆盖 - 列表在最后一次迭代时不会改变;打印的元素也不会改变。
Here is a snippet of code which gives the output:
0 1 2 2
. I had expected the output3 3 3 3
sincea[-1]
accesses the number 3 in the list. The explanation given online says "The value ofa[-1]
changes in each iteration" but I don't quite understand how or why. Any explanations would be great!a = [0, 1, 2, 3] for a[-1] in a: print(a[-1])
解决方案What's happening here is a list is mutated during looping.
Let's consider following code snippet:
a = [0, 1, 2, 3] for a[-1] in a: print a
Output is:
[0, 1, 2, 0] [0, 1, 2, 1] [0, 1, 2, 2] [0, 1, 2, 2]
Each iteration:
- reads value from position currently pointed by internal pointer
- immediately assigns it to last element in list
- after that last element is printed on standard output
So it goes like:
- internal pointer points to first element, it's 0, and last element is overwritten with that value; list is
[0, 1, 2, 0]
; printed value is0
- internal pointer points to second element, it's 1, and last element is overwritten with that value; list is
[0, 1, 2, 1]
; printed value is1
- (...)
- at last step, internal pointer points to last element; last element is overwritten by itself - list does not change on last iteration; printed element also does not change.
这篇关于循环和遍历列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- 内部指针指向第一个元素,它是0,最后一个元素被该值覆盖;列表是
$ b $立即将它分配给列表中的最后一个元素