在 if 语句中使用别名
Using alias in an if statement
在 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 3.8 开始,您可以使用:
if value := f(x):
# Do something with value
是的,从 python3.8
开始,在以后的版本中,有。通过使用有争议的海象 (:=
) 运算符,例如
$ 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 语句的测试又用作语句内的值? 我的意思是:
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 3.8 开始,您可以使用:
if value := f(x):
# Do something with value
是的,从 python3.8
开始,在以后的版本中,有。通过使用有争议的海象 (:=
) 运算符,例如
$ 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
...
>>>