arfarinha
arfarinha

Reputation: 172

How do you apply a list of lambda functions to a single element using an iterator?

I want to apply a list of lambda functions to a single element using an iterable that has to be created with yield.

The list of lambda functions would have something like:

[<function <lambda> at 0x1d310c8>, <function <lambda> at 0x1d355f0>]

And I want to apply every function, from left to right , to a single element using yield to construct an iterable to iterate the list

Upvotes: 3

Views: 956

Answers (5)

ovgolovin
ovgolovin

Reputation: 13410

Do you necessarily need a yield statement?

Because there is another way to create generator: to use ().

applied_it = (f(item) for f in functions)

Upvotes: 1

Steven Rumbalski
Steven Rumbalski

Reputation: 45552

def apply_all(functions, item):
    for f in functions:
        yield f(item)

Example usage:

functions = [type, id, hex]
for result in apply_all(functions, 55):
    print result

gives

<type 'int'>
20326112
0x37

Upvotes: 7

jsbueno
jsbueno

Reputation: 110516

def apply(value, lambda_list):
    for function in lambda_list:
          yield (function(value))

Upvotes: 0

Wilduck
Wilduck

Reputation: 14126

Give this a shot:

def lambda_apply(unnamed_funcs, element):
    for unnamed in unnamed_funcs:
        yield unnamed(element)

>>> l = [lambda x: x**2, lambda x: 2*x]
>>> el = 5

>>> for y in lambda_apply(l, el):
...     print y
... 
25
10

Note that this works not only for a list of unnamed functions, but any list of functions of arity 1. This is because all functions, named or not, are first class objects in python. You can store them in a list, and use them later, as demonstrated above.

Upvotes: 3

David Zwicker
David Zwicker

Reputation: 24328

The answer could be formulated as

import numpy as np

def apply_funcs( funcs, val ):
    for func in funcs:
        yield func(val)

my_funcs = [lambda x: np.cos(x), np.sin, np.tan]
my_val = 0.1

for res in apply_funcs( my_funcs, my_val ):
    print res

where the apply_funcs function does the trick and the rest is just for demonstration purposes.

Upvotes: 2

Related Questions