Hovestar
Hovestar

Reputation: 1627

Python Map() reverse

Is there a function that takes a list of functions and an input and outputs a list of the functions operation on the input?

So like map, but backwards:

>>>map(lambda x: 2*x,[1,2,3,4,5,6,7,8,9])
[2, 4, 6, 8, 10, 12, 14, 16, 18]
>>>reverseMap([lambda x: x**2,lambda x: x**3],3)
[9,27]

Upvotes: 3

Views: 1533

Answers (3)

arshajii
arshajii

Reputation: 129507

You can use a simple list comprehension:

>>> funcs = [lambda x: x**2, lambda x: x**3]
>>> 
>>> [f(3) for f in funcs]
[9, 27]

Upvotes: 6

NPE
NPE

Reputation: 500367

How about simply:

In [1]: [f(3) for f in lambda x: x**2,lambda x: x**3]
Out[1]: [9, 27]

You can wrap it in a function if you like.

Upvotes: 4

mdml
mdml

Reputation: 22882

You can in fact use a map to do this:

>>> map(lambda f: f(3), [lambda x: x**2,lambda x: x**3])
[9, 27]

Use the list of functions you want to apply as the iterable, and then apply each of them to your input (in this case 3).

Upvotes: 13

Related Questions