2

我对python中变量的范围感到困惑。这是我正在尝试做的一个玩具示例:

a = True
enumerated_set = enumerate(['tic','tac','toe'])
for i,j in enumerated_set:
    if a == True:
        print j

我得到的结果是:

tic
tac
toe

现在,

print a

返回

`True`

如果我再跑

for i,j in enumerated_set:
    if a == True:
        print j

我没有输出。

我很困惑......因为 global a = True,为什么在第二个循环期间没有执行打印。

我感谢您的帮助。

编辑:另一个我很困惑的例子

y = 'I like this weather'.split()
for item in y:
    for i,j in enumerated_set:
         if a == True: 
             print j

也没有输出....

4

3 回答 3

7

你的布尔值实际上不是问题。那总是True

enumerated_set是一个发电机。一旦你循环通过它,它就会筋疲力尽。您需要创建一个新的。

In [9]: enumerated_set = enumerate(['tic','tac','toe'])

In [10]: enumerated_set.next()
Out[10]: (0, 'tic')

In [11]: enumerated_set.next()
Out[11]: (1, 'tac')

In [12]: enumerated_set.next()
Out[12]: (2, 'toe')

In [13]: enumerated_set.next()
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
/usr/local/<ipython-input-13-7b0a413e4250> in <module>()
----> 1 enumerated_set.next()

StopIteration: 
于 2012-11-08T23:49:41.027 回答
1

This is not due to scope, it is due to the nature of enumerate, which creates a generator, not a list. Generators are single-use: they pop off elements in sequence, they don't create a list which can be evaluated again. This saves memory.

If you wanted to iterate over enumerated_set twice, you might do this:

enumerated_set = list(enumerate(['tic','tac','toe']))

于 2012-11-08T23:51:59.490 回答
1

It is nothing to do with the a variable. You are using an enumerator object,and in the first loop it is gone to its end. You have to recreate it for the second loop.

于 2012-11-08T23:52:47.577 回答