lambda 表达式的包装器
我在 python 中有一些函数,它接受两个输入,进行一些操作,然后返回两个输出。我想重新排列输出参数,因此我在原始函数周围编写了一个包装函数,该函数使用新的输出顺序创建一个新函数
def rotate(f):
h = lambda x,y: -f(x,y)[1], f(x,y)[0]
return h
f = lambda x, y: (-y, x)
h = rotate(f)
但是,这给出了一条错误消息:
NameError: global name 'x' is not defined
x
is an argument to一个 lambda 表达式,那么为什么必须定义它呢?
预期的行为是 h
应该是一个与 lambda x,y: (-x,-y)
相同的新函数
I have functions in python that take two inputs, do some manipulations, and return two outputs. I would like to rearrange the output arguments, so I wrote a wrapper function around the original function that creates a new function with the new output order
def rotate(f):
h = lambda x,y: -f(x,y)[1], f(x,y)[0]
return h
f = lambda x, y: (-y, x)
h = rotate(f)
However, this is giving an error message:
NameError: global name 'x' is not defined
x
is an argument to a lambda expression, so why does it have to be defined?
The expected behavior is that h
should be a new function that is identical to lambda x,y: (-x,-y)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要在 lambda 表达式两边添加括号:
否则,Python 会将代码解释为:
并且
h
是一个 2 元组。You need to add parentheses around the lambda expression:
Otherwise, Python interprets the code as:
and
h
is a 2-tuple.优先级有问题。只需使用额外的括号:
There is problem with precedence. Just use additional parentheses: