Python 带三元运算符的Walrus运算符的正确语法是什么?
查看和,Python的三元运算符等价物是:Python 带三元运算符的Walrus运算符的正确语法是什么?,python,python-3.x,conditional-operator,walrus-operator,Python,Python 3.x,Conditional Operator,Walrus Operator,查看和,Python的三元运算符等价物是: a if condition else b 看着和,我明白了海象操作员是什么: := 现在我尝试将“walrus运算符赋值”和“三元运算符条件检查”组合成一个语句,类似于: other_func(a) if (a := some_func(some_input)) else b 例如,请考虑下面的片段: do_something(list_of_roles) if list_of_roles := get_role_list(username)
a if condition else b
看着和,我明白了海象操作员是什么:
:=
现在我尝试将“walrus运算符赋值”和“三元运算符条件检查”组合成一个语句,类似于:
other_func(a) if (a := some_func(some_input)) else b
例如,请考虑下面的片段:
do_something(list_of_roles) if list_of_roles := get_role_list(username) else "Role list is [] empty"
我没能把心思集中在语法上。尝试了各种组合后,每次解释器抛出SyntaxError:invalid syntax
。我的python版本是3.8.3
我的问题是在三元运算符中嵌入walrus运算符的正确语法是什么?从语法上讲,您只是缺少一对括号
do_something(list_of_roles) if (list_of_roles := get_role_list(username)) else "Role list is [] empty"
如果查看语法,
:=
被定义为高级namedexpr\u测试的一部分
构造:
namedexpr_test: test [':=' test]
而条件表达式是一种测试
:
test: or_test ['if' or_test 'else' test] | lambdef
这意味着不能在条件表达式中使用
:=
,除非它出现在嵌套表达式中。那么您尝试过吗?发生什么事了?@Chris,是的,我试过了。我可能想到的所有排列和组合都以语法错误告终。很久以后,我放弃了。我更新了我的问题。很抱歉,我刚才漏掉了信息。作为一个傻瓜的缺点:-(当有疑问时,加上一些括号。多年来我发现这条规则非常有用。