Taiwosam Taiwosam - 2 months ago 15
Python Question

Use map and filter instead of a for loop?

How do I write an equivalent of the code below using map and filter?

res = []
for x in range(5):
if x % 2 == 0:
for y in range(5):
if y % 2 == 1:
res.append((x, y))


This is the expected result:

[(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)]


Here's the code I wrote, but it doesn't seem to work:

list( map(( lambda x,y: (x,y)), filter((lambda x: x%2 == 0), range(5)), filter((lambda y: y%2 != 0), range(5))))

Answer

You can write it as (in Python 2.x):

xs = filter(lambda x: x % 2 == 0, range(5))
ys = filter(lambda y: y % 2 == 1, range(5))
res = [(x, y) for x in xs for y in ys]

This also uses a list comprehension.

In Python 3.x:

xs = list(filter(lambda x: x % 2 == 0, range(5)))
ys = list(filter(lambda y: y % 2 == 1, range(5)))
res = [(x, y) for x in xs for y in ys]
Comments