![](/img/trans.png)
[英]how to convert 2d list to 2d native python array not numpy array?
[英]How to apply filter function on 2D array/list in python
我只想从二维列表 list1 = [[-1,2,3,4,-2], [-4,3,2]] 中找到正数
output = [[2,3,4],[3,2]]
到目前为止我试过print(list(filter(lambda x: (x>0), [[-1,2,3,4,-2], [-4,3,2]]) ))
但我在过滤器中应用二维列表时遇到问题。
这是不可读的,只是为了回答你的问题,使用map
上面的filter
前任:
list1 = [[-1,2,3,4,-2], [-4,3,2]]
print(list(map(lambda x:list(filter(lambda y: (y>0), x)), list1)))
# Better to use nested list comprehension
print([[j for j in i if j >0] for i in list1])
Output:
[[2, 3, 4], [3, 2]]
这种方式行不通,因为在“lambda x: (x>0)”中,x 是一个列表而不是一个数字。 要使其工作,您需要 map 二维列表并过滤每个元素/子列表。
list1 = [[-1,2,3,4,-2], [-4,3,2]]
output = list(
map(
lambda l: list(filter(lambda x: x > 0, l)),
list1
)
)
print(output)
这是执行给出正确结果的代码: https://ideone.com/gN5Xct
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.