C# 的条件运算符 (?) 的 Python 版本

标签 python conditional-operator

我看到了this question但它使用 ??运算符作为空检查,我想将其用作 bool true/false 测试。

我在 Python 中有这段代码:

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

在 C# 中我可以这样写:

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

在 Python 中有类似的方法吗?

最佳答案

是的,你可以这样写:

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

这叫做 Conditional Expression在 Python 中。

关于C# 的条件运算符 (?) 的 Python 版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7692121/

相关文章:

python - 检测组中每个 Sprite 或对象的鼠标单击

python - python 是否有一个内置函数可以为 None 获取 0

java - 条件(三元)运算符代码风格

java - 编译器为什么以及如何区别对待这两个条件?

html - Ul 扇区向左移动

python - 使用 Python 的三元运算符结合 lambda 的意外输出

Python Facebook 'NoneType object error'

python - 在 Django 中创建一个包含动态数据的 3 列 HTML 表格

python - 使用用户定义的分类方案绘制等值线图(使用 geopandas)

c++ - C 和 C++ 之间的条件运算符差异