Skip to main content
 首页 » 编程设计

Python 相当于设置 if not null

2025年05月04日9cloudgamer

在 ruby 中我可以这样做:

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 中是否有类似的单行代码?

请您参考如下方法:

只需使用 or运算符(operator)。从链接页面:

x or y: if x is false, then y, else 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