繁体   English   中英

语句前的 python 条件

[英]python condition before statement

在 Go 中,可以在语句之前使用条件句:

if num := 9; num < 0 

我想在 python 中做同样的事情。 我正在创建一个 function,它返回结果的状态以及成功时的实际结果,如下所示:

def myfunc:
  val = 0
  if val > 0:
    return [ True, val ]
  else:
    return [ False, val ]

所以我想像这样使用它:

if res, val = myfunc() TEST FOR res:
  do_something()

从 Python 3.8 开始,您可以使用赋值表达式

我们将 output 分配给一个元组out ,并测试其第一项是否为True

def myfunc(val):
  if val > 0:
    return [ True, val ]
  else:
    return [ False, val ]

if (out := myfunc(5))[0]:
    print(out)
else:
    print('That was False')
# [True, 5]


if (out := myfunc(-2))[0]:
    print(out)
else:
    print('That was False')
# That was False

遗憾的是,我们不能即时解包元组:

if ((res, val) := myfunc(-2))[0]:
    print(val)
else:
    print('That was False')

     File "<ipython-input-10-03724761d41a>", line 20
    if ((res, val) := myfunc(-2))[0]:
        ^
SyntaxError: cannot use named assignment with tuple

这在 python 中是不可能的。 只需将其放在两行中,例如

res, val = myfunc()
if res:
    do_something()

所以似乎不可能。 我想像在 Go 中那样对同一语句进行分配和测试。

关闭这个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM