循环和遍历列表 [英] for loops and iterating through lists

查看:160
本文介绍了循环和遍历列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一段代码,它给出了输出: 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


解决方案 div>

这里发生了什么是一个列表在循环过程中发生了变化。



让我们考虑下面的代码片段:

  a = [0, 1,2,3] 
为a:
中的[-1]打印

输出是:

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

每次迭代:


  • 从内部指针当前指向的位置读取值

  • $ b $立即将它分配给列表中的最后一个元素
  • 最后一个元素打印在标准输出中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 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
    

    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 is 0
    • 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 is 1
    • (...)
    • 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屋!

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