Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Map and Filter code that operates on lists

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)))))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading