用常量x映射lambda x,y
有什么优雅的方法可以把一个有两个参数的 lambda
函数应用到一个值的列表上,其中第一个参数是固定的,第二个参数来自一个 list
呢?
举个例子:
lambda x,y: x+y
x='a'
y=['2','4','8','16']
期望的结果:
['a2','a4','a8','a16']
注意事项:
- 这只是一个例子,实际的
lambda
函数会更复杂 - 假设我不能使用列表推导式
7 个回答
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))
11
你也可以用闭包来解决这个问题。
x='a'
f = lambda y: x+y
map(f, ['1', '2', '3', '4', '5'])
>>> ['a1', 'a2', 'a3', 'a4', 'a5']
18
你可以使用 itertools.starmap
。
a = itertools.starmap(lambda x,y: x+y, zip(itertools.repeat(x), y))
a = list(a)
这样你就能得到你想要的结果。
顺便说一下,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]