Haskell provides the feature something li开发者_StackOverflow中文版ke f = f1 . f2
How can I mimic that with Python?
For example, if I have to do the 'map' operation two times, is there any way to do something like map . map in Python?
x = ['1','2','3'] x = map(int,x) x = map(lambda i:i+1, x)
I think you are looking for function composition in Python.
You can do this:
f = lambda x: f1(f2(x))
There have been several proposals for a compose
operation, but none have been formalized. In the meantime it is possible to use a list comprehension or a generator expression to apply complex transformations to a sequence.
def compose(f,g):
return lambda x: f(g(x))
def inc(x): return x+1
map(compose(inc, int), ['1', '2', '3'])
# [2, 3, 4]
>>> import functional, functools, operator >>> f1 = int >>> f2 = functools.partial(operator.add, 1) >>> f = functional.compose(f1, f2) >>> x = map(f, ['1', '2', '3'])
There's a good recipe for this here.
精彩评论