gpt4 book ai didi

python - 在 python 中的子列表上使用 map 和 filter 函数

转载 作者:太空宇宙 更新时间:2023-11-04 09:51:15 25 4
gpt4 key购买 nike

L = [[5, 0, 6], [7, 22], [0, 4, 2], [9, 0, 45, 17]]

我确实有这个列表,我的任务是删除 0。我必须同时使用map()filter() 函数。

提示是这个任务可以通过使用 map、filter 和 lambda 表达式的单个表达式来解决。

我已经尝试解决这个问题很长一段时间了,但我就是不明白。您不必完全解决它,但我们将不胜感激。

我假设我使用 map() 来迭代外部列表,但是我如何调用带有子列表的 filter()

L2 = map(lambda x: filter(lambda x: x<>0 ,L),L)

最佳答案

使用 mapfilter 你可以编写以下内容

>>> list(map(lambda i: list(filter(lambda i: i != 0, i)), L))
[[5, 6], [7, 22], [4, 2], [9, 45, 17]]

就其值(value)而言,我更喜欢嵌套列表理解

>>> [[i for i in j if i != 0] for j in L]
[[5, 6], [7, 22], [4, 2], [9, 45, 17]]

关于python - 在 python 中的子列表上使用 map 和 filter 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47744366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com