3

私はPythonが初めてで、この形式の三項演算子を使用しようとしています(そう思います)

value_true if <test> else value_false

コードのスニペットを次に示します。

expanded = set()

while not someExpression:

    continue if currentState in expanded else expanded.push(currentState)

    # some code here

しかし、Python はそれを好まず、次のように言います。

SyntaxError: invalid syntax (pointed to if)

修正方法は?

4

1 に答える 1

10

ステートメントではなくforを使用した Python の三項演算。表現は価値のあるものです。

例:

result = foo() if condition else (2 + 4)
#        ^^^^^                   ^^^^^^^
#      expression               expression

ステートメント ( 、 などのコード ブロックcontinue) には、次forを使用しますif

if condition:
     ...do something...
else:
     ...do something else...

やりたいこと:

expanded = set()

while not someExpression:
    if currentState not in expanded: # you use set, so this condition is not really need
         expanded.add(currentState)
         # some code here
于 2012-10-10T21:58:38.097 に答える