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
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 3.8开始,您可以使用:
if value := f(x):
# Do something with value