Python版本的C#条件运算符(?) [英] Python version of C#'s conditional operator (?)

查看:47
本文介绍了Python版本的C#条件运算符(?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了这个问题但它使用??运算符作为null检查,我想将其用作布尔真/假测试。

I saw this question but it uses the ?? operator as a null check, I want to use it as a bool true/false test.

我在Python中有以下代码:

I have this code in Python:

if self.trait == self.spouse.trait:
    trait = self.trait
else:
    trait = defualtTrait

在C#中,我可以这样写:

In C# I could write this as:

trait = this.trait == this.spouse.trait ? this.trait : defualtTrait;

在Python中有类似的方法吗?

Is there a similar way to do this in Python?

推荐答案

是的,您可以编写:

trait = self.trait if self.trait == self.spouse.trait else defaultTrait

这称为 Python中的条件表达式

这篇关于Python版本的C#条件运算符(?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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