Pet*_*ter 4 python if-statement assign
有没有比更简单的替代方案
res = returns_value_or_none(arg)
if res:
do_something_with(res)
Run Code Online (Sandbox Code Playgroud)
或者
if returns_value_or_none(arg):
do_something_with(returns_value_or_none(arg))
Run Code Online (Sandbox Code Playgroud)
一种将赋值和if条件结合到一个语句中的语句?
小智 9
对于 Python 3.8+,PEP 572引入了赋值表达式
这允许使用符号分配给表达式中的变量NAME := expr。它可以在 if 语句中使用,例如:
if (match := pattern.search(data)) is not None:
# Do something with match
Run Code Online (Sandbox Code Playgroud)