Python:嵌套生成器表达式的可变范围

时间:2015-06-09 11:37:37

标签: python scope nested generator list-comprehension

有人可以解释以下内容:

这符合我的预期:

>>> [(x, [x for i in xrange(2)]) for x in xrange(3)]
[(0, [0, 0]), (1, [1, 1]), (2, [2, 2])]

使用生成器x评估为2

>>> [(x, list(x for i in xrange(2))) for x in xrange(3)]
[(0, [2, 2]), (1, [2, 2]), (2, [2, 2])]

这似乎是因为生成器表达式中的x取自全局范围

>>> x = -1
>>> [(x, list(x for i in xrange(2))) for x in xrange(3)]
[(0, [-1, -1]), (1, [-1, -1]), (2, [-1, -1])]
>>> del x
>>> [(x, list(x for i in xrange(2))) for x in xrange(3)]
Traceback (most recent call last):
  File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 4.0.4\helpers\pydev\pydevd_exec.py", line 3, in Exec
exec exp in global_vars, local_vars
  File "<input>", line 1, in <module>
  File "<input>", line 1, in <genexpr>
NameError: global name 'x' is not defined

为什么?

0 个答案:

没有答案