shivam seth
shivam seth

Reputation: 19

How do you use lambda and map instead of list comprehension do iterate over multiple lists?

I'm trying to generate the same list using lambda and map which is e as in d. However, it does not result in a readable list and instead just the positions of maps.

a=[1,2,3,4,5]
b=[1,2,3]
d=[v+w for v in a for w in b]
e=list(map(lambda v: (lambda w:v+w, b),a))

Upvotes: 0

Views: 329

Answers (3)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96349

Actually, you cannot just do this with map in any straightforward way, because the equivalent operation here would be a flat-map operation, so you'd have to include a reduce and materialize the iterator in the internal map. It won't be efficient, i.e. it will be quadratic time, but something like

from functools import reduce
reduce(lambda x,y: x+y, map(lambda v: list(map(lambda w: v+w, b)), a))

Would work. If you want to "cheat", use itertools, but this will be efficient:

from itertools import chain
list(chain.from_iterable(map(lambda v: map(lambda w: v+w, b), a)))

Upvotes: 0

CMMCD
CMMCD

Reputation: 360

I would not recommend using lambdas for this (or in general) but you can do this with only built in functions.

e = sum(list(map(lambda v: list(map(lambda w: v + w, b)), a)), [])

# Explanation
# Inner map lambda to add each value from b to v
map(lambda w: v + w, b))

# Outer map lambda that loops through each item in a and runs the inner lambda
map(lambda v: list(map(lambda w: v + w, b)), a)

# Flatten result array
sum(result, [])

Upvotes: 1

Green Cloak Guy
Green Cloak Guy

Reputation: 24711

Your lambda needs to have two inputs in order to add two values (or else the first value needs to be already-accessible). I would submit that, instead of nesting lambdas inside each other, just use something like itertools.product() to get every (a, b) pair, and then submit each tuple to the lambda.

e = list(map(lambda t:t[0]+t[1], list(itertools.product(a,b))))

in which case, why even bother with a lambda?

e = list(map(sum, list(itertools.product(a,b))))

Upvotes: 1

Related Questions