Home > Software engineering >  Python Map and Filter code that operates on lists
Python Map and Filter code that operates on lists

Time:12-05

I'm trying to use map and filter to operates on lists db, and dc.

db = [3, 5, 7, 3, 2, 7, 9] 
dc = [1, 0, 1, 0, 1, 0, 1]

to produce the output list of dd = [25,9,49] i.e., element of db is squared if the corresponding entry in dc is a 0.

Here's what I have so far.

db = [3, 5, 7, 3, 2, 7, 9]
dc = [1, 0, 1, 0, 1, 0, 1]
dd = list(map(lambda x: x ** 2, filter(lambda y: y == 0, dc)))
print(dd)

Can someone point me in the right direction?

CodePudding user response:

The right direction would probably be to not use filter but zip:

db = [3, 5, 7, 3, 2, 7, 9]
dc = [1, 0, 1, 0, 1, 0, 1]

dd = [b**2 for b,c in zip(db, dc) if not c]

Output: [25,9,49]

using filter

This requires to find a common ground, here the index, but the code is much less nicer...

list(map(lambda x: db[x]**2,  filter(lambda y: dc[y]==0, range(len(dc)))))
  • Related