这个条件运算符做什么?

2024-10-02 08:30:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我真的不知道如何解读他们,我还在努力找出他们到底在做什么。。你知道吗

color = self.color2

color = self.fill1 if color == self.fill2 else self.fill2

这到底是什么意思?你知道吗


Tags: selfifelsecolorcolor2fill2fill1
3条回答

这是一个conditional expressionPEP-308。你知道吗

像这样的事情

x = true_value if condition else false_value 

也可以写成

if condition:
    x = true_value
else:
    x = false_value

这被称为conditional expression。你知道吗

The expression x if C else y first evaluates the condition, C (not x); if C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.

因此,您的具体示例相当于:

if color == self.fill2:
    color = self.fill1
else:
    color = self.fill2

这不是列表理解。它是一种句法上的糖分。 讽刺的是,这是为了提高可读性。你知道吗

可以解释为:

if color == self.fill2:
    color = self.fill1
else:
    color = self.fill2

相关问题 更多 >

    热门问题