为什么这个简单的条件表达式不起作用?(复制)

时间:2022-08-05 16:46:46

This question already has an answer here:

这个问题已经有了答案:

Very simple line:

非常简单的线:

i = 3
a = 2 if i in [1, 3, 6] else a = 7

fails with:

失败:

SyntaxError: can't assign to conditional expression

whereas expanded as:

而扩展为:

if i in [1, 3, 6]:
    a = 2
else:
    a = 7

works fine.

工作很好。

2 个解决方案

#1


15  

You are using it wrong. Use it this way:

你用错了。这样使用它:

a = 2 if i in [1, 3, 6] else 7

#2


5  

Should be

应该是

 a = 2 if i in [1, 3, 6] else 7

You can read it as:

你可以这样读:

 a = (((2 if i in [1, 3, 6] else 7)))

which is to say that the expression on the right side of the assignment sign is fully evaluated and the result then assigned to the left side. The expression itself is two values separated by the condition.

也就是说,赋值符号右边的表达式被完全赋值,结果被赋值给左边。表达式本身是由条件分隔的两个值。

#1


15  

You are using it wrong. Use it this way:

你用错了。这样使用它:

a = 2 if i in [1, 3, 6] else 7

#2


5  

Should be

应该是

 a = 2 if i in [1, 3, 6] else 7

You can read it as:

你可以这样读:

 a = (((2 if i in [1, 3, 6] else 7)))

which is to say that the expression on the right side of the assignment sign is fully evaluated and the result then assigned to the left side. The expression itself is two values separated by the condition.

也就是说,赋值符号右边的表达式被完全赋值,结果被赋值给左边。表达式本身是由条件分隔的两个值。