奇怪的循环语句 [英] Weird for loop statement

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

问题描述

我看到这个for循环,我不明白为什么最后一个打印是2.
为什么不是3?

  a = [0,1,2,3] 

for a [-1] a:
print(a [-1])$ ​​b $ b



out:

  0 
1
2
2
循环使用 a [ - code $] 1] 作为目标变量,从输入迭代中分配每个值:

 用于< target> in< iterable> 

循环的 a 列表到该目标, a [-1] 。所以 也是同一个列表中的最后一个元素。所以列表改变循环:

 >>> a = [0,1,2,3] 
>>>对于a中的[-1]:
...打印
...
[0,1,2,0]#将a [0] == 0赋值给a [ -1](或a [3])
[0,1,2,1]#将a [1] == 1赋值给a [-1]
[0,1,2,2 ]#分配a [2] == 2给[-1]
[0,1,2,2]#赋值[3] == 2(自上一次迭代以来)为[-1]

一次最后一次迭代赋予 a [2] a [3] (或 a [-2] a [-1] ),这就是为什么当最后一次迭代发生时,你再次看到 2



for 循环语法;它需要一种通用的 target_list 的分配对象,就像一个 assigment声明。你不仅限于赋值中的简单名字,也不限于循环中的


I saw this for loop and I didn't quite understood why the last print is 2. Why it isn't 3 ?

a = [0, 1, 2, 3]

for a[-1] in a:
    print(a[-1])

out:

0
1
2
2

解决方案

The for loop uses a[-1] as a target variable, assigning each value from the input iterable:

for <target> in <iterable>

The for loop assigns each value in the a list to that one target, a[-1]. That happens to also be the last element in that same list.

So the list changes with each step through the loop:

>>> a = [0, 1, 2, 3]
>>> for a[-1] in a:
...     print a
...
[0, 1, 2, 0]  # assigned a[0] == 0 to a[-1] (or a[3])
[0, 1, 2, 1]  # assigned a[1] == 1 to a[-1]
[0, 1, 2, 2]  # assigned a[2] == 2 to a[-1]
[0, 1, 2, 2]  # assigned a[3] == 2 (since the previous iteration) to a[-1]

The one-but-last iteration assigns puts a[2] into a[3] (or a[-2] into a[-1]), and that is why, when the last iteration takes place, you see 2 again.

See the for loop grammar; it takes a generic target_list for the assignment target, just like an assigment statement. You are not limited to just simple names in assignments, and neither are you in a for loop.

这篇关于奇怪的循环语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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