Bha*_*wan 4 python conditional-operator python-3.x walrus-operator
看看Python-Dev和StackOverflow,Python 的三元运算符等价物是:
a if condition else b
Run Code Online (Sandbox Code Playgroud)
看看PEP-572和StackOverflow,我明白了 Walrus 算子是什么:
:=
Run Code Online (Sandbox Code Playgroud)
现在我试图将“海象运算符的赋值”和“三元运算符的条件检查”组合成一个语句,例如:
other_func(a) if (a := some_func(some_input)) else b
Run Code Online (Sandbox Code Playgroud)
例如,请考虑以下代码段:
do_something(list_of_roles) if list_of_roles := get_role_list(username) else "Role list is [] empty"
Run Code Online (Sandbox Code Playgroud)
我无法理解语法。尝试了各种组合后,每次解释器抛出SyntaxError: invalid syntax. 我的 python 版本是 3.8.3。
我的问题是在三元运算符中嵌入海象运算符的正确语法是什么?
Lar*_*erg 13
对于那些寻求简短答案或未能像我一样快速掌握已接受答案的人:
\n>>> variable = foo if (foo := \'parentheses!!\') else \'otherwise\'\n>>> # \xe2\x96\xb2 \xe2\x96\xb2\n>>> # \xe2\x95\xb0\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x95\xaf\n>>> variable\nparentheses!!\nRun Code Online (Sandbox Code Playgroud)\n
从语法上讲,您只是缺少一对括号。
do_something(list_of_roles) if (list_of_roles := get_role_list(username)) else "Role list is [] empty"
Run Code Online (Sandbox Code Playgroud)
如果您查看语法,:=则被定义为高级namedexpr_test构造的一部分:
namedexpr_test: test [':=' test]
Run Code Online (Sandbox Code Playgroud)
而条件表达式是一种test:
test: or_test ['if' or_test 'else' test] | lambdef
Run Code Online (Sandbox Code Playgroud)
这意味着:=不能在条件表达式中使用,除非它出现在嵌套表达式中。