Python 中有没有一种方法可以使用函数结果作为 if 语句的测试和语句内的值? 我的意思是:
if f(x) as value:
# Do something with value
不是
value = f(x)
if value:
# Do something with value
或
with f(x) as value:
if value:
# Do something with value
最佳答案
是的,从 python3.8
及更高版本开始,有。通过使用有争议的 walrus(:=
) 运算符,例如,
$ python3.8
Python 3.8.0 (default, Oct 15 2019, 11:27:32)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(x): return x
...
>>> if value := f(1):
... print(value)
...
1
>>> if value := f(0):
... print(value) # won't execute
...
>>>
关于python - 在 if 语句中使用别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58724761/