2011-10-04 96 views
5

什麼是map兩個參數的優雅方法lambda函數爲一個值列表,其中第一個參數是常量,第二個參數是listmap lambda x,y with constant x

實施例:

lambda x,y: x+y 
x='a' 
y=['2','4','8','16'] 

預期的結果:

['a2','a4','a8','a16'] 

注:

  • 這只是一個例子,實際lambda函數是更復雜
  • 假設一世不能使用列表理解

回答

15

您可以使用itertools.starmap

a = itertools.starmap(lambda x,y: x+y, zip(itertools.repeat(x), y)) 
a = list(a) 

,你會得到你想要的輸出。

BTW,既itertools.imap和Python3的map將接受如下:

itertools.imap(lambda x,y: x+y, itertools.repeat(x), y) 

默認Python2的map不會在y末停止,將插入None小號...


但理解是更好

[x + num for num in y] 
+1

+1用於提示pythonic列表理解而不是總體ol映射函數(= - 雖然我剛注意到提問者狀態「假設我不能使用列表理解」 –

10

的Python 2.x的

from itertools import repeat 

map(lambda (x, y): x + y, zip(repeat(x), y)) 

Python 3.x都有

map(lambda xy: ''.join(xy), zip(repeat(x), y)) 
+0

只是意識到它不會工作Python 3 ... – JBernardo

+0

@JBernardo,他們是否將'在簽名中解壓縮'走了?我似乎記得沿着這些線。 –

+0

是的,這就是爲什麼我在我的答案上建議'starmap'。 – JBernardo

5
def prependConstant(x, y): 
    return map(lambda yel: x + yel, y) 
9

你也可以使用封此

x='a' 
f = lambda y: x+y 
map(f, ['1', '2', '3', '4', '5']) 
>>> ['a1', 'a2', 'a3', 'a4', 'a5'] 
4
['a' + x for x in y] 

,或者如果你真的需要一個調用的:

def f(x, y): 
    return x + y 

[f('a', x) for x in y] 
2

你有使用拉姆達?

>>> x='a' 
>>> y=['2','4','8','16'] 
>>> map(x.__add__, y) 
['a2', 'a4', 'a8', 'a16'] 
>>> 
-1

順便說一句,既itertools.imap和Python3的地圖將接受如下:

itertools.imap(拉姆達X,Y:X + Y,itertools.repeat(X)中,y) 默認的Python2地圖不會停止在y的末尾,並會插入Nones ...

我只是想添加到這個答案是在Python 2.x中,你可以像

map(lambda x,y: x+y, itertools.repeat(x, len(y))) 

有所收穫itertools停止迭代。

相關問題