问题
In ruby I can do this:
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
Is there a similar one-liner in Python?
回答1:
Just use the or operator. From the linked page:
x or y: if x is false, then y, else x
Example:
In [1]: 1 or 2
Out[1]: 1
In [2]: None or 2
Out[2]: 2
In [3]: 1 or None
Out[3]: 1
回答2:
Python's or operator is pretty much the equivalent of Ruby's || -- and None can be used in Python somewhat similarly to how nil is in Ruby.
So, for example,
a = None or 2
would set a to 2.
You can also use a richer "ternary" operator, something if condition else somethingelse -- a or b is the same as a if a else b -- but clearly or is more concise and readable when what you want to do is exactly the semantics it supports.
回答3:
Don't forget about modern if-else syntax:
x = a if a is not None else 999
(or whatever condition you need). This let you test for non-None and is not prone to empty list and similar problems.
General syntax is
ValueToBeUsedIfConditionIsTrue if Condition else ValueToBeUsedIfConditionIsFalse
来源:https://stackoverflow.com/questions/28308648/python-equivalent-of-setting-if-not-null