I want to find only positive numbers from 2D list list1 = [[-1,2,3,4,-2], [-4,3,2]]
output = [[2,3,4],[3,2]]
I tried so far print(list(filter(lambda x: (x>0), [[-1,2,3,4,-2], [-4,3,2]]) ))
but I'm having trouble applying 2D list in filter.
This is not readable but just to answer your question use map above filter
Ex:
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]]
That way won't work because in "lambda x: (x>0)" x is a list and not a number. To make it work you need to map the 2D list and filter each element/sublist.
list1 = [[-1,2,3,4,-2], [-4,3,2]]
output = list(
map(
lambda l: list(filter(lambda x: x > 0, l)),
list1
)
)
print(output)
This is the code executed giving the right result: https://ideone.com/gN5Xct