简体   繁体   English

不能分配给条件表达式

[英]cannot assign to conditional expression

if i+1 < stages[i]: tried[i] = (tried[i] + 1) if tried[i] != None else tried[i] = 0

if i+1 < stages[i]: tried[i] = (tried[i] + 1) if tried[i] != None else tried[i] = 0 ^ SyntaxError: can't assign to conditional expression如果 i+1 < 阶段 [i]:试过 [i] = (试过 [i] + 1) 如果试过 [i] != 没有其他试过 [i] = 0 ^ 语法错误:无法分配给条件表达式

I got an error of cannot assign to conditional expression .我收到了cannot assign to conditional expression的错误。 Not sure which part I did wrong.不知道我做错了哪一部分。

Should be:应该:

if i+1 < stages[i]: tried[i] = (tried[i] + 1) if tried[i] != None else 0

without the last triend[i] = 0 , just 0 (also triend would be probably wrong anyway).没有最后的triend[i] = 0 ,只有0 (无论如何, triend也可能是错误的)。

The overall structure you're looking for, since you are trying to accomplish an assignment with multiple conditional expressions, is this: variable = expression condition else expression condition ... else expression .您正在寻找的整体结构,因为您试图用多个条件表达式完成赋值,是这样的: variable = expression condition else expression condition ... else expression You can even use parentheses to remind yourself of how it will be parsed: variable = ( expression condition else expression condition ... else expression ).您甚至可以使用括号来提醒自己它将如何解析:变量= (表达式条件else表达式条件... else表达式)。 The total conditional expression must end with "else".整个条件表达式必须以“else”结尾。

For instance, I have the following code:例如,我有以下代码:

x = 5
if x == 1:
    a = '1'
elif x == 2:
    a = '2'
else:
    a = '3'
print(a)

Using a conditional expression, it becomes:使用条件表达式,它变成:

x = 5
a = '1' if x == 1 else '2' if x == 2 else '3'
print(a)

I'm not sure what your assignment and conditional expressions我不确定你的赋值和条件表达式是什么

if i+1 < stages[i]: tried[i] = (tried[i] + 1) if tried[i] != None else tried[i] = 0

would look like when expanded, as some information is missing:展开时看起来像,因为缺少一些信息:

missing_expression = '?'
if i+1 < stages[i]:
    tried[i] = (tried[i] + 1)
elif tried[i] != None:
    tried[i] = missing_expression
else:
    tried[i] = 0

When the missing expression is supplied, your conditional expression should look like:提供缺少的表达式时,您的条件表达式应如下所示:

tried[i] = (tried[i] + 1) if i+1 < stages[i] else missing_expression if tried[i] != None else 0

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

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