对于一个值列表的map两个参数lambda函数的优雅方法是什么,其中第一个参数是常量而第二个是从list?
例:
lambda x,y: x+y
x='a'
y=['2','4','8','16']
Run Code Online (Sandbox Code Playgroud)
预期结果:
['a2','a4','a8','a16']
Run Code Online (Sandbox Code Playgroud)
笔记:
JBe*_*rdo 17
您可以使用 itertools.starmap
a = itertools.starmap(lambda x,y: x+y, zip(itertools.repeat(x), y))
a = list(a)
Run Code Online (Sandbox Code Playgroud)
并获得所需的输出.
顺便说itertools.imap一下,Python3和Python3 map都会接受以下内容:
itertools.imap(lambda x,y: x+y, itertools.repeat(x), y)
Run Code Online (Sandbox Code Playgroud)
默认的Python2 map将不会在结束时停止y并将插入Nones ...
但理解力要好得多
[x + num for num in y]
Run Code Online (Sandbox Code Playgroud)
Igo*_*gor 11
你也可以使用闭包
x='a'
f = lambda y: x+y
map(f, ['1', '2', '3', '4', '5'])
>>> ['a1', 'a2', 'a3', 'a4', 'a5']
Run Code Online (Sandbox Code Playgroud)
Ada*_*ner 10
Python 2.x
from itertools import repeat
map(lambda (x, y): x + y, zip(repeat(x), y))
Run Code Online (Sandbox Code Playgroud)
Python 3.x
map(lambda xy: ''.join(xy), zip(repeat(x), y))
Run Code Online (Sandbox Code Playgroud)
def prependConstant(x, y):
return map(lambda yel: x + yel, y)
Run Code Online (Sandbox Code Playgroud)
['a' + x for x in y]
Run Code Online (Sandbox Code Playgroud)
或者,如果您真的需要可调用的话:
def f(x, y):
return x + y
[f('a', x) for x in y]
Run Code Online (Sandbox Code Playgroud)