for 循环和遍历列表 [英] for loops and iterating through lists
本文介绍了for 循环和遍历列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是给出输出的代码片段:0 1 2 2
.我原以为输出 3 3 3 3
因为 a[-1]
访问列表中的数字 3.网上给出的解释说a[-1]
的值在每次迭代中都会改变",但我不太明白如何或为什么.任何解释都会很棒!
Here is a snippet of code which gives the output: 0 1 2 2
. I had expected the output 3 3 3 3
since a[-1]
accesses the number 3 in the list. The explanation given online says "The value of a[-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
输出为:
[0, 1, 2, 0]
[0, 1, 2, 1]
[0, 1, 2, 2]
[0, 1, 2, 2]
每次迭代:
- 从内部指针当前指向的位置读取值
- 立即将其分配给列表中的最后一个元素
- 在最后一个元素被打印到标准输出之后
所以它是这样的:
- 内部指针指向第一个元素,它是0,最后一个元素被那个值覆盖;列表是
[0, 1, 2, 0]
;打印值为0
- 内部指针指向第二个元素,它是1,最后一个元素被那个值覆盖;列表是
[0, 1, 2, 1]
;打印值为1
- (...)
- 最后一步,内部指针指向最后一个元素;最后一个元素被自己覆盖 - 列表在最后一次迭代时不会改变;打印元素也不会改变.
- 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.
这篇关于for 循环和遍历列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文