11

受此答案中的构造的启发,我正在尝试执行以下操作:

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]
4

1 回答 1

1

我知道您的示例和错误报告中的代码确实在金字塔框架的交互式外壳(pshell,使用 ipython 0.12!)中成功运行,尽管我记得以前遇到过这个问题。关键是 ipython >= 0.11 它使用不同的代码。据我所知,0.10 代码仍然会有这个错误。

这是金字塔 pshell.py 的简化摘录

def make_ipython_v0_11_shell():
    try:
        from IPython.frontend.terminal.embed import (
            InteractiveShellEmbed)
        IPShellFactory = InteractiveShellEmbed
    except ImportError:
        return None

    def shell(env, help):
        IPShell = IPShellFactory(banner2=help + '\n', user_ns=env)
        IPShell()

   return shell

def make_ipython_v0_10_shell():
    try:
        from IPython.Shell import IPShellEmbed
        IPShellFactory = IPShellEmbed
    except ImportError:
        return None

    def shell(env, help):
        IPShell = IPShellFactory(argv=[], user_ns=env)
        IPShell.set_banner(IPShell.IP.BANNER + '\n' + help + '\n')
        IPShell()

    return shell
于 2013-08-13T05:17:46.147 回答