受此答案中的构造的启发,我正在尝试执行以下操作:
values = range(3)
vector = np.random.randint(3, size=(5,))
f = lambda x: x in values
result = [f(a) for a in values]
但我明白了global name 'values' is not defined
。
如果我尝试上面链接的解决方案,我会得到同样的错误,即:
A = [[0,1,2], [1,2,3], [2,3,4]]
v = [1,2]
B = [map(lambda val: val in v) for a in A]
自该解决方案发布以来,Python 是否发生了变化?(我正在使用2.7.4)。如果是这样,我如何访问 lambda 函数中的外部变量?我应该将其声明为全局吗?将其作为另一个输入传递?
更新1:
我只是在IPython (1.0)的嵌入式 shell中注意到这个问题。
更新 2:
GitHub 上有一张关于该主题的 IPython票证,但不清楚问题是否已解决。
更新 3(不是来自 OP):
该错误可在 django 的 shell 中重现(感谢@Ashwini)
$ ./manage.py shell
Python 2.7.4 (default, Apr 19 2013, 18:32:33)
Type "copyright", "credits" or "license" for more information.
IPython 0.13.2 -- An enhanced Interactive Python.
In [1]: import numpy as np
In [2]: values = range(3)
In [3]: vector = np.random.randint(3, size=(5,))
In [4]: f = lambda x: x in values
In [5]: result = [f(a) for a in values]
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in <module>()
----> 1 result = [f(a) for a in values]
/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in <lambda>(x)
----> 1 f = lambda x: x in values
NameError: global name 'values' is not defined
In [6]: values
Out[6]: [0, 1, 2]