开发者

[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]
开发者_JS百科

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()?


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


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


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]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜