有没有人能解释一下我到底做错了什么-
multiArray = [
['one', 'two', 'three', 'four', 'five'],
['one', 'two', 'three', 'four', 'five'],
['one', 'two', 'three', 'four', 'five']
]
search ='four'
p1 = list(filter(lambda outerEle: search == outerEle, multiArray[0]))
p = list(filter(lambda multiArrayEle: list(filter(lambda innerArrayEle: search == innerArrayEle, multiArrayEle)), multiArray))
print (p1)
print (p)我在这里得到的结果是
['four']
[['one', 'two', 'three', 'four', 'five'], ['one', 'two', 'three', 'four', 'five'], ['one', 'two', 'three', 'four', 'five']]当我期待的时候
[['four'],['four'],['four']]发布于 2019-03-17 02:21:41
虽然@fuglede的答案确实是您问题的答案,但是您可以通过将外部filter更改为map来归档您想要的结果
p = list(map(lambda multiArrayEle: list(filter(lambda innerArrayEle: search == innerArrayEle, multiArrayEle)), multiArray))发布于 2019-03-17 02:14:29
在第二个filter中,您使用list作为谓词(而不是像在第一个filter中那样使用简单的bool );现在,这将隐式地将内置方法bool应用于每个元素list,并且对于列表l,当l为非空时,bool(l)恰好为真:
In [4]: bool([])
Out[4]: False
In [5]: bool(['a'])
Out[5]: True例如,这允许您挑选出列表列表中的所有非空列表:
In [6]: ls = [['a'], [], ['b']]
In [7]: list(filter(lambda l: l, ls))
Out[7]: [['a'], ['b']]因此,在您的例子中,在一天结束时,您的filter最终会给出所有出现'four'的列表,这就是所有的列表。
从您给定的示例中,由于所有输入都是相同的,所以您尝试实现的目标并不是一目了然的,但我的猜测是如下所示:
In [19]: multiArray = [
...: ['one', 'two', 'three', 'four', 'five', 'four'],
...: ['one', 'two', 'three', 'for', 'five'],
...: ['one', 'two', 'three', 'four', 'five']
...: ]
In [20]: [list(filter(lambda x: x == search, l)) for l in multiArray]
Out[20]: [['four', 'four'], [], ['four']]https://stackoverflow.com/questions/55199947
复制相似问题