Synapse
Synapse

Reputation: 1624

[python]: problem about passing map() with a func and 2 lists with different dimensions

suppose I got a list, say

lst1 = [1,2,3,4]

and another list, say

lst2 = [8,9]

and a func, say

func = lambda x,y: x+y

what I want to do is to produce a list whose element is the sum of lst1's element and lst2's. i.e., I want to produce a lst with lst1 and lst2, and lst should be

[1+8+9, 2+8+9, 3+8+9, 4+8+9].

how can I do it with map()?

Upvotes: 0

Views: 102

Answers (3)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29113

Your func is simply add operator so you can use 'add' from operator module the following way:

from operator import add
lst = [1,2,3,4]
sLst = [8,9]
map(lambda x: add(x, sum(sLst)), lst)
>>> [18,19,20,21]

It is ok to use map - but usually it is not so fast as simple list comprehension that also looks pretty clear:

from operator import add
lst = [1,2,3,4]
sLst = [8,9]
[add(x, sum(sLst)) for x in lst]
>>> [18,19,20,21]

Upvotes: 0

miku
miku

Reputation: 188054

>>> map(lambda x: x + sum(lst2), lst1)
[18, 19, 20, 21]

Upvotes: 6

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798716

>>> map(lambda x, y: x + y, lst1, itertools.repeat(sum(lst2), len(lst1)))
[18, 19, 20, 21]

Upvotes: 1

Related Questions