lapin lapin - 4 months ago 16x
Python Question

map - convert a nested for loop to map equivalent

Example :

>>>for x in iterable1:
... expression

The map form would be :

>>>map(lambda x:expression,iterable1)

How do I extend this to nested for?

Example :

>>>for x in itr1:
... for y in itr2:
... expr

Without using comprehensions.

Edit: Using only map.


Bear with me on this one. Not an explanation but this worked after 2 days. Using only map and list. It's bad code. Suggestions to shorten the code are welcome. Python 3 solution

Example using list comprehension:

>>> a=[x+y for x in [0,1,2] for y in [100,200,300]]
>>> a

Example using for:

>>>for x in [0,1,2]:
...    for y in [100,200,300]:
...        a.append(x+y)

Now example using only map:

>>>list(map(lambda x:n.extend(map(x,[100,200,300])),map(lambda x:lambda y:x+y,[0,1,2])))

Much smaller python2.7 solution:

>>>map(lambda x:m.extend(x),map(lambda x:map(x,[100,200,300]),map(lambda x:lambda y:x+y,[0,1,2])))