简体   繁体   English

为什么在将lambda函数赋值给变量时需要括号?

[英]Why do I need brackets around lambda functions when assigning them to variables?

I've just stumbled about some unexpected behavior in Python in the below code snippet 我刚刚在下面的代码片段中偶然发现了Python中的一些意外行为

b = False

func_1 = lambda x,y:set([x]) == y if b else lambda x,y: x in y
func_2 = None   

if not b:
    func_2 = lambda x,y : x in y
else:
    func_2 = lambda x,y:set([x]) == y 

print(func_1("Hello", set(["Hello", "World"])))
print(func_2("Hello", set(["Hello", "World"])))

The output is 输出是

<function <lambda>.<locals>.<lambda> at 0x7f7e5eeed048>
True

However, when adding brackets around the lambdas everything works as expected: 但是,当在lambdas周围添加括号时,一切都按预期工作:

func_1 = (lambda x,y:set([x]) == y) if b else (lambda x,y: x in y)
# ...

The output then is 输出然后是

True
True

Why do I need those brackets? 为什么我需要这些括号? I thought the initial expression was equivalent to the long if-else construct. 我认为初始表达式等同于长if-else结构。

It's just standard precedence rules. 这只是标准的优先规则。 Your first expression is being parsed as: 您的第一个表达式被解析为:

lambda x,y:set([x]) == (y if b else lambda x,y: x in y)

So you need to add the parentheses to create the correct precedence. 因此,您需要添加括号以创建正确的优先级。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我需要lambda将函数应用于Pandas Dataframe? - Why do I need lambda to apply functions to a Pandas Dataframe? Python:为什么解压字典时不需要 2 个变量? - Python: Why do I not need 2 variables when unpacking a dictionary? 为什么我需要在这些 Python Tkinter 函数中使用星号和一些随机变量才能正常工作? - Why do I need an asterisk and some random variable in these Python Tkinter functions for them to work properly? 如何在python中存储字符串变量并在函数中传递它们? - How do to store variables which are strings in python and pass them around in functions? 为什么需要限定局部变量? - Why do I need to qualify local variables? 为什么我需要在 TensorFlow 中初始化变量? - Why do I need to initialize variables in TensorFlow? 什么时候需要在 Python 中的 integer 周围添加引号 - When do I need to add quotation marks around an integer in Python 分配时 Python 字典键错误 - 我该如何解决这个问题? - Python dictionary key error when assigning - how do I get around this? 我需要删除括号以进行标记化吗? 正则表达式分词器 - Do i need to remove brackets for tokenization? RegexpTokenizer 为什么这些物体如此快速地在屏幕周围反弹。我该如何放慢速度呢? - Why do these objects bounce around the screen so fast. How do I slow them down
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM