Python的等价的,如果不为空的设置(Python equivalent of setting i

2019-10-21 19:03发布

在红宝石我可以这样做:

1.9.3-p448 :001 > a = 1 || 2
 => 1 
1.9.3-p448 :004 > a = nil || 2
 => 2 
1.9.3-p448 :005 > a = 1 || nil
 => 1 

是否有一个相似的衬垫在Python?

Answer 1:

只需使用or操作者。 从链接页面:

x或y:如果x是假的,那么y,否则x

例:

In [1]: 1 or 2
Out[1]: 1

In [2]: None or 2
Out[2]: 2

In [3]: 1 or None
Out[3]: 1


Answer 2:

Python的or运营商几乎是Ruby的相当于|| -并None能够在Python中使用有些类似于如何nil在红宝石。

因此,例如,

a = None or 2

将设置a2

您还可以使用更丰富的“三元”运算符, something if condition else somethingelse - a or b是相同的a if a else b -但显然or更加简洁易读,当你想要做的是完全语义它支持。



Answer 3:

不要忘了现代化的if-else语法:

x = a if a is not None else 999

(或任何条件,你需要)。 这让你测试非无,不容易发生空列表和类似的问题。

一般语法

ValueToBeUsedIfConditionIsTrue if Condition else ValueToBeUsedIfConditionIsFalse


文章来源: Python equivalent of setting if not null
标签: python null