为什么内联IF赋值需要else语句?

Gra*_*rus 2 python

x = 'foo' if x == 'bar' else x
Run Code Online (Sandbox Code Playgroud)

现在这将等于:

x = 'foo' if x == 'bar' 
Run Code Online (Sandbox Code Playgroud)

但这会返回"无效语法"错误.是否有这样的原因,或者设计决策背后的原因是什么?因为如果函数是多行的(例如#2的函数):

if x == 'foo':
    x = 'bar'
Run Code Online (Sandbox Code Playgroud)

它完美无缺.

Amb*_*ber 7

对于Python解释器,这行代码......

x = 'foo' if x == 'bar' else x
Run Code Online (Sandbox Code Playgroud)

不是这样解释的......

(x = 'foo') if x == 'bar' else (x = x)
Run Code Online (Sandbox Code Playgroud)

而是被解释为这样:

x = ('foo' if x == 'bar' else x)
Run Code Online (Sandbox Code Playgroud)

这是因为x if cond else yPython中的三元运算符是表达式而不是语句 - 它可以在您指定值的任何位置使用.

因此,您也可以使用它,例如,在您没有执行任务的情况下:

print("hi" if x == 'bar' else "bye")
Run Code Online (Sandbox Code Playgroud)

因为它是一个表达式,所以它总是需要能够解析为某个值,以便可以在表达式使用的任何上下文中使用该值.


Dav*_*ers 6

这是因为它不是陈述而是表达.它必须评估某些内容,因此您无法排除else条件.此外,因为它是一个表达式,你不能(真的,你不应该)做任何会改变状态的事情.

更多信息:https://docs.python.org/2/reference/expressions.html#conditional-expressions

当然,这样的事情是完全可能的:

class C(object):
    def foo(self):
        self.y = 1
        return 'foo'

c = C()

c.foo() if True else 'bar'

print c.y

# Prints '1'
Run Code Online (Sandbox Code Playgroud)

......所以三元表达中的变异状态实际上并未被禁止; 它只是不推荐.