Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Iterating over lists in lists with map()

So my intention is to iterate over lists in lists with map, filter and lambda e.g.:

[ [33,3,3,0] , [34,1,0,4] ] should result in [ [33,3,3] , [34,1,4] ]

   def no_zeros(lst):
      a=map(filter(lambda x:(y==0 for y in x) ,lst),lst)
      print (list(a))
      #(says that filter is not callable)

I know that this code won't work but i do not know what exactly i do wrong since i'm still kind of new to lambda,etc.I already tried different stuff , like moving the filter after the lambda,but that did not seem to work either . Im gratefull for any kind of tipps or help.

like image 570
asdas sadsad Avatar asked Oct 15 '25 04:10

asdas sadsad


2 Answers

map applies the function in first parameter to the second parameter. It tries to call your filter object...

A fixed version would be:

list(map(lambda z: list(filter(None,z)),lst))

(still not very clear even if it yields the expected result... it took me 3 or 4 tries to get it right by trial & error, and the fact that filter & map need to be iterated upon in Python 3 doesn't help and kills the whole hype about those fashionable keywords)

At this point of lambda/map/filter complexity you'd be better off with a list comprehension:

lst = [ [33,3,3,0] , [34,1,0,4] ]

result = [ [x for x in sl if x] for sl in lst]

print(result)

result:

[[33, 3, 3], [34, 1, 4]]
like image 144
Jean-François Fabre Avatar answered Oct 17 '25 21:10

Jean-François Fabre


The thing is that map expects a function/callable as a first argument but you're giving it the result of a filter.

You can fix this by applying filter to the sublists iterated by map:

def no_zeros(lst):
    a = map(lambda x: filter(lambda y: y != 0, x), lst)
    print(list(a))

By the way, you can do the same thing with list comprehensions:

def no_zeros(lst):
    a = [[y for y in x if y != 0] for x in lst]
    print(a)
like image 40
Matias Cicero Avatar answered Oct 17 '25 21:10

Matias Cicero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!