我对使用 lambda 过滤列表的理解是,过滤器将返回列表中所有为 lambda 函数返回 True 的元素。在这种情况下,对于以下代码,
inputlist = []
inputlist.append(["1", "2", "3", "a"])
inputlist.append(["4", "5", "6", "b"])
inputlist.append(["1", "2", "4", "c"])
inputlist.append(["4", "5", "7", "d"])
outputlist = filter(lambda x: (x[0] != "1" and x[1] != "2" and x[2] != "3"), inputlist)
for item in outputlist: print(item)
输出应该是
['4', '5', '6', 'b']
['1', '2', '4', 'c']
['4', '5', '7', 'd']
但是我得到的输出是
['4', '5', '6', 'b']
['4', '5', '7', 'd']
如果我使用,我会得到预期的输出
outputlist = filter(lambda x: (x[0] != "1" or x[1] != "2" or x[2] != "3"), inputlist)
我在这里做什么傻事?还是我的理解不正确?
原文由 user3300676 发布,翻译遵循 CC BY-SA 4.0 许可协议
x = ['1', '2', '4', 'c']
,x[1]=='2'
(x[0] != "1" and x[1] != "2" and x[2] != "3")
False
When conditions are joined by
and
, they returnTrue
only if all conditions areTrue
, and if they are joined byor
, they返回True
当其中第一个被评估为True
。