可以定义包装函数,应用给定函数
f
在某些情况下
cond
保留,然后将该函数应用于列表中的每个元素。
def repeat(func, cond, x):
while cond(x):
x = func(x)
return x
>>> f = lambda x: x + 5
>>> [repeat(f, lambda x: x < 18, item) for item in [1, 3, 2]]
[21, 18, 22]
或者使用
functools.partial
要创建要应用的新函数,例如,
map
:
>>> import functools
>>> g = functools.partial(repeat, f, lambda x: x < 18)
>>> list(map(g, [1, 3, 2]))
[21, 18, 22]