asdas sadsad
asdas sadsad

Reputation: 43

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.

Upvotes: 4

Views: 8646

Answers (5)

bierschi
bierschi

Reputation: 322

Another solution might be:

def no_zeros(lst):
   if isinstance(lst, list):
      for i in lst:
          while 0 in i:
              i.remove(0)
      print(lst)
   else:
      raise TypeError("lst must be type of list")

Upvotes: 1

Jean-François Fabre
Jean-François Fabre

Reputation: 140287

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]]

Upvotes: 9

Matias Cicero
Matias Cicero

Reputation: 26331

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)

Upvotes: 2

Paul Panzer
Paul Panzer

Reputation: 53089

Here is one possibility:

import itertools
a = [ [33,3,3,0] , [34,1,0,4] ] 
list(map(list, map(filter, itertools.repeat(bool), a)))
# [[33, 3, 3], [34, 1, 4]]

Upvotes: 1

Abdul Faiz
Abdul Faiz

Reputation: 59

lst = list(map(lambda k: list(filter(lambda l: l != 0, k)), lst))

This should do the trick. You need apply a lambda on each element in the list through a filter. Be aware nested lambdas are ugly.

Upvotes: 1

Related Questions