在C#中有一個null-coalescing operator(寫爲??
),可實現簡單的(短)空檢查分配期間:是否存在與C#空合併運算符相當的Python?
string s = null;
var other = s ?? "some default value";
有沒有一個python等效?
我知道我能做到:
s = None
other = s if s else "some default value"
但有一個更短的方式(這裏我不需要重複s
)?
在C#中有一個null-coalescing operator(寫爲??
),可實現簡單的(短)空檢查分配期間:是否存在與C#空合併運算符相當的Python?
string s = null;
var other = s ?? "some default value";
有沒有一個python等效?
我知道我能做到:
s = None
other = s if s else "some default value"
但有一個更短的方式(這裏我不需要重複s
)?
other = s or "some default value"
好的,必須澄清or
運營商是如何工作的。它是一個布爾運算符,因此它在布爾上下文中工作。如果這些值不是布爾值,則爲了操作員的目的將它們轉換爲布爾值。
請注意,or
運營商不只返回True
或False
。相反,如果第一個操作數的計算結果爲true,則返回第一個操作數;如果第一個操作數的計算結果爲false,則返回第二個操作數。
在這種情況下,表達式x or y
返回x
如果它是True
或者轉換爲布爾值時返回true。否則,它返回y
。在大多數情況下,這將有助於爲C♯的空合併運算的同樣的目的,但要記住:
42 or "something" # returns 42
0 or "something" # returns "something"
None or "something" # returns "something"
False or "something" # returns "something"
"" or "something" # returns "something"
如果您使用的變量s
持有的東西,或者是給一個參考一個類的實例或None
(只要你的類沒有定義成員__nonzero__()
和__len__()
),則使用與空合併運算符相同的語義是安全的。
事實上,Python的這種副作用甚至可能是有用的。由於您知道哪些值的計算結果爲false,因此您可以使用它來觸發默認值,而不使用None
(例如,錯誤對象)。
在某些語言中,此行爲被稱爲Elvis operator。
這個工作是否一樣?我的意思是,如果's`是一個有效值但不是真的,它會破壞嗎? (我不知道Python,所以我不確定'truthy'的概念是否適用。) – cHao 2011-02-12 15:33:42
除了常量「0」,「None」和空容器(包括字符串)返回FALSE。其他大部分事情都被視爲真實。我想說,這裏的主要危險是你會得到一個真正的但沒有字符串的值,但這在某些程序中不會成爲問題。 – kindall 2011-02-12 15:52:58
如果s是None **或False **,則使用此_other_將獲得默認值,這可能不是所期望的。 – pafcu 2011-02-12 16:15:22
嚴格,
other = s if s is not None else "default value"
否則S = false將成爲 「默認值」,這可能不是想要的結果。
如果你想使這個更短,儘量
def notNone(s,d):
if s is None:
return d
else:
return s
other = notNone(s, "default value")
這裏將返回不是無的第一個參數的函數:
def coalesce(*arg):
return reduce(lambda x, y: x if x is not None else y, arg)
# Prints "banana"
print coalesce(None, "banana", "phone", None)
減少()可能不必要地遍歷所有參數即使第一個參數不是None,所以你也可以使用這個版本:
def coalesce(*arg):
for el in arg:
if el is not None:
return el
return None
In add銀行足球比賽到利亞諾的關於「或」行爲答案: 它的「快」
>>> 1 or 5/0
1
所以有時它可能是東西有用的快捷方式一樣
object = getCachedVersion() or getFromDB()
兩個功能下我已經發現處理很多變量測試時非常有用。
def nz(value, none_value, strict=True):
''' This function is named after an old VBA function. It returns a default
value if the passed in value is None. If strict is False it will
treat an empty string as None as well.
example:
x = None
nz(x,"hello")
--> "hello"
nz(x,"")
--> ""
y = ""
nz(y,"hello")
--> ""
nz(y,"hello", False)
--> "hello" '''
if value is None and strict:
return_val = none_value
elif strict and value is not None:
return_val = value
elif not strict and not is_not_null(value):
return_val = none_value
else:
return_val = value
return return_val
def is_not_null(value):
''' test for None and empty string '''
return value is not None and len(str(value)) > 0
````操作符被建議爲[PEP 505](https://www.python.org/dev/peps/pep-0505/)。 – 2016-10-20 18:39:17