带三元运算符的Walrus运算符的正确语法是什么? [英] What is the correct syntax for Walrus operator with ternary operator?
问题描述
查看 Python-Dev 和< a href = https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator> StackOverflow ,Python的三元运算符等效为:
Looking at Python-Dev and StackOverflow, Python's ternary operator equivalent is:
a if condition else b
查看 PEP-572 和 StackOverflow ,我了解Walrus运算符是什么:
Looking at PEP-572 and StackOverflow, I understand what Walrus operator is:
:=
现在,我尝试将海象运算符的分配和三元操作员的条件检查变成单个语句,例如:
Now I'm trying to to combine the "walrus operator's assignment" and "ternary operator's conditional check" into a single statement, something like:
other_func(a) if (a := some_func(some_input)) else b
例如,请考虑以下代码段:
For example, please consider the below snippet:
do_something(list_of_roles) if list_of_roles := get_role_list(username) else "Role list is [] empty"
我无法将语法全神贯注。尝试各种组合后,解释器每次抛出 SyntaxError:无效语法
。我的python版本是3.8.3。
I'm failing to wrap my mind around the syntax. Having tried various combinations, every time the interpreter throws SyntaxError: invalid syntax
. My python version is 3.8.3.
我的问题是将海象运算符嵌入三元运算符中的正确语法是什么?
推荐答案
语法上,您只是缺少一对括号。
Syntactically, you are just missing a pair of parenthesis.
do_something(list_of_roles) if (list_of_roles := get_role_list(username)) else "Role list is [] empty"
如果您查看语法,则:=
被定义为高级 namedexpr_test
构造的一部分:
If you look at the grammar, :=
is defined as part of a high-level namedexpr_test
construct:
namedexpr_test: test [':=' test]
而条件表达式是 test的一种
:
test: or_test ['if' or_test 'else' test] | lambdef
这意味着:=
不能使用条件表达式中的条件表达式,除非它出现在嵌套表达式中。
This means that :=
cannot be used in a conditional expression unless it occurs inside a nested expression.
这篇关于带三元运算符的Walrus运算符的正确语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!