python中的神秘的循环 [英] Mysterious for loop in python

查看:144
本文介绍了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 $

解决方案 在Python中被重载。




  • x在exp 中,你问是 x
  • // 中,您告诉Python 中的每个元素 exp ,称它为 x


  • $ b

    后者会将 exp x ,并且用这个值执行循环的主体,所以在第一次迭代 x 是在第二个 2 中分配 1 ,并在最后一个 5 。此外, 在循环之后保持这个值!

    因此, ,假设已经定义了变量 x ,但是有一些其他的值, x在exp 中会返回 False ,并在循环之后返回 True ,因为 x 仍然被赋值最后一个值是 exp


    Let exp = [1,2,3,4,5]

    If I then execute x in exp, it will give me False. But if I execute :

    for x in exp:
        if x==3:
            print('True')
    

    Then execute x in exp, it returns True. What's happening here? I didn't assign anything to x. Did I? I am really confused.

    **EDIT:**Sorry if I didn't say this before: x is not defined before.

    Answer

    Thank you everyone. I understand it now. the elements of 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.

    解决方案

    Seems like you stumbled about in being somewhat overloaded in Python.

    • with x in exp, you are asking "Is x in exp?"
    • with for x in exp: ..., you tell Python "For each element in exp, call it x and do ..."

    The latter will assign each of the values in 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!

    Thus, before the loop, assuming that the variable 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.

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

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