python中的神秘的循环 [英] Mysterious for loop in python
问题描述
让 exp = [1,2,3,4,5]
code> x在exp 中,它会给我 False
。但是,如果我执行:
for x in exp:
if x == 3:
print 'true')
然后在exp中执行 x
,它会返回 True
。这里发生了什么事?我没有分配任何东西给x。我有吗?我很困惑。
**编辑:**对不起,如果我以前没说过: x
以前没有定义过。
回答
谢谢大家。我现在明白了将 exp
的元素分配给 x
,因为 exp
是迭代。最后一行代码中的 x in exp
等于 True
,因为最后一个元素已被赋值给<$ c $
- 用
x在exp
中,你问是x
- // 中,您告诉Python 中的每个元素
exp
,称它为x
- with
x in exp
, you are asking "Isx
inexp
?" - with
for x in exp: ...
, you tell Python "For each element inexp
, call itx
and do ..."
$ b
后者会将 因此, ,假设已经定义了变量 Let If I then execute Then execute **EDIT:**Sorry if I didn't say this before: Thank you everyone. I understand it now. the elements of Seems like you stumbled about The latter will assign each of the values in Thus, before the loop, assuming that the variable 这篇关于python中的神秘的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! exp
到 x
,并且用这个值执行循环的主体,所以在第一次迭代 x
是在第二个 2
中分配 1
,并在最后一个 5
。此外, 在循环之后保持这个值!
x
,但是有一些其他的值, x在exp
中会返回 False
,并在循环之后返回 True
,因为 x
仍然被赋值最后一个值是 exp
。exp = [1,2,3,4,5]
x in exp
, it will give me False
. But if I execute :for x in exp:
if x==3:
print('True')
x in exp
, it returns True
. What's happening here? I didn't assign anything to x. Did I? I am really confused.x
is not defined before.Answer
exp
is assigned to x
as exp
is iterated over. And x in exp
equals True
in the last line of code because the last element has been assigned to x
.in
being somewhat overloaded in Python.
exp
to x
, one after the other, and execute the body of the loop with that value, so in the first iteration x
is assigned 1
, in the second 2
, and in the last 5
. Also, x
keeps this value after the loop!x
is defined but has some other value, x in exp
will return False
, and after the loop, it returns True
, because x
is still assigned the last value from exp
.