問題描述
Python 2.7:使用 reduce 驗證元素是否在列表中 (Python 2.7: Using reduce to verify that elements are in a list)
在嘗試使用 reduce 函數時,我觀察到我無法向自己解釋的行為。假設有 2 個列表:
a = ["a", "b", "c", "z"]
b = ["b", "z", "a"]
我想驗證列表 b 的所有元素是否都在列表中 a 使用 reduce。所以,我嘗試:
reduce(lambda x,y: (x in a) and (y in a), b)
並得到 False 而不是預期的 True。
那麼,為什麼我會得到 False?
PS:我知道還有其他方法可以驗證是否所有列表的元素都在另一個列表中,fi使用集合和 issuperset。我只是想知道為什麼 reduce 函數會這樣工作。
參考解法
方法 1:
Your code:
b = ["b", "z", "a"]
reduce(lambda x,y: (x in a) and (y in a), b)
is equivalent to:
(("b" in a) and ("z" in a)) in a and ("a" in a)
which calculates to:
(True in a) and ("a" in a)