【问题标题】:Using alias in an if statement [duplicate]在 if 语句中使用别名 [重复]
【发布时间】:2019-11-06 15:12:29
【问题描述】:

在 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 运算符。 if value := f(x):..# do_stuff(value)

标签: python if-statement alias


【解决方案1】:

是的,在 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
... 
>>> 

【讨论】:

    【解决方案2】:

    从新的python 3.8开始,您可以使用:

    if value := f(x): 
        # Do something with value
    

    【讨论】:

      猜你喜欢
      • 2013-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-06
      • 1970-01-01
      • 2011-06-09
      • 2012-01-12
      • 1970-01-01
      相关资源
      最近更新 更多