Stagg Stagg - 10 months ago 58
Python Question

Alternate through lambda functions

I have to make a function that takes a list and and maps two lambda functions alternatively. Like this:

>>> alternateMap(lambda x:x+1, lambda y:y+10, [1, 2, 3, 4])

So, the first function(lambda x:x+1) applies to the first element and the third element, the second functio(lambda y:y+10) applies to the second and fourth elements.

So far I have this:

for i in l:
a = map(function1,l)
i +=2
for n in l[1:]:
a = map(function2,l)
i+= 2
return a

But unfortunately it's not correct.


This works for any number of functions.

>>> from itertools import cycle
>>> func_cycle = cycle([lambda x:x+1, lambda y:y+10])
>>> [next(func_cycle)(item) for item in [1, 2, 3, 4]]
[2, 12, 4, 14]

You stated in comments elsewhere that you need a version that uses map. Here you go:

import itertools

class FunctionCycler(object):
    def __init__(self, *funcs):
        self.func_cycle = itertools.cycle(funcs)
    def __call__(self, *args, **kwds):
        # passes args and kwds to next function and returns result
        return next(self.func_cycle)(*args, **kwds)

func_cycle = FunctionCycler(lambda x:x+1, lambda y:y+10)
map(func_cycle, [1, 2, 3, 4])