Python三元运算符和else中的赋值 [英] Python ternary operator and assignment in else

查看:64
本文介绍了Python三元运算符和else中的赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

三元运算符非常有用,为什么它在这种特殊情况下不起作用:

Ternary operator is very useful, why it does not work in this particular case:

c="d"
d={}
d[c]+=1 if c in d else d[c]=1

它给出:

d[c]+=1 if c in d else d[c]=1
                           ^
SyntaxError: invalid syntax

在这里我没有看到任何错误,因为没有三元运算符的相同的东西也可以工作:

I don't see nothing wrong here since the same thing without the ternary operator works:

c="d"
d={}
if c in d:
    d[c]+=1
else:
    d[c]=1

推荐答案

三元运算符适用于表达式,而不适用于语句.分配是一个声明.使用常规的if/else.

The ternary operator works on expressions, not statements. Assignment is a statement. Use a regular if/else.

这篇关于Python三元运算符和else中的赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆