Python 2.7:使用 reduce 驗證元素是否在列表中 (Python 2.7: Using reduce to verify that elements are in a list)


問題描述

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)

(by Atsvetkzvone)

參考文件

  1. Python 2.7: Using reduce to verify that elements are in a list (CC BY‑SA 2.5/3.0/4.0)

#reduce #Python






相關問題

Lapack 的行縮減 (Lapack's row reduction)

泡菜cython類 (pickle cython class)

將列表列表減少為字典,以子列表大小為鍵,出現次數為值 (Reduce list of list to dictionary with sublist size as keys and number of occurances as value)

使用 map/reduce 在列表中添加一對數字的差異 (Adding difference of pair of numbers in list using map/reduce)

Python 2.7:使用 reduce 驗證元素是否在列表中 (Python 2.7: Using reduce to verify that elements are in a list)

使用 map/reduce 計算總數 (Using map/reduce to calculate totals)

Swift reduce - 為什麼 value 是可選的? (Swift reduce - why is value optional?)

獲取具有對像一鍵值的數組的平均值 - Javascript (Get the avarage value of array with objects one key value - Javascript)

如何將數據數組轉換為在顫振/飛鏢中展開或折疊的小部件列表? (How to convert an array of data to a list of widgets with expand or fold in flutter/dart?)

樹的字符串路徑 (JavaScript) (String-path to Tree (JavaScript))

如何重命名對像數組中對象的所有鍵? (How does one rename all of an object's keys within an array of objects?)

使用reduce轉換一個js對象 (transform a js object using reduce)







留言討論