Python :: Ternary Operator ::无法使用多个语句

时间:2018-04-17 11:14:41

标签: python if-statement conditional ternary-operator

我的情况是这样的。

a = 3
b = 5
c = 7
# using ternary operator now,
print a; c = 1 if a < b else print b ; c = 2

当我在两侧都使用赋值运算符时会引发此错误

SyntaxError: can't assign to conditional expression

如果我像这样使用它,它可以正常工作。

a = 1 ; c = 1 if a < b else b 

所以问题是如何在Python Ternary Operator中使用多个语句?

2 个答案:

答案 0 :(得分:1)

简短回答:你不能在三元表达式中使用语句。

三元表达式并不意味着包含语句,只包含表达式。在Python2中,ARRAY=([a]=1 [b]=2 [c]=3) name="ARRAY" eval a=\${$name['a']} eval b=\${$name['b']} eval c=\${$name['c']} echo "$a$b$c" Output>>> 123 eval $array['a']=10 echo ${ARRAY['a']} Output>>> 10 是一个语句,因此将它放在三元组中是无效的语法。

print

三元组的目的是条件返回值。因此,两个分支都应该是最好返回相同类型值的表达式。

c = 1 if a < b else print b
#                   ^^^^^^^ In Python2 `print` is a statement

任何其他情况都应该使用 if-statement

# This is a good use of ternary expressions
c = 1 if a < b else 2

答案 1 :(得分:0)

您不能使用三元表达式执行多语句。但是你可以这样做。我不确定它是否会运行得更快。

a = 3
b = 5
c = 7

def onTrue():
    print(a)
    c = 1

def onFalse():
    print(b)
    c = 2

onTrue() if a < b else onFalse