Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting a subset of functions from a list of functions in python

Tags:

python

I have a list: mylist = [1,2,5,4,7,8] I have defined a number of functions that operate on this list. For example:

def mean(x): ...
def std(x): ...
def var(x): ...
def fxn4(x): ...
def fxn5(x): ...
def fxn6(x): ...
def fxn7(x): ...

Now I am given a list of function names that I want to apply on mylist.

for ex: fxnOfInterest = ['mean', 'std', 'var', 'fxn6']

What is the most pythonic way to call these function?

like image 748
learner Avatar asked Sep 26 '15 22:09

learner


1 Answers

I don't think that there is a pythonic™ way to solve the question. But in my code it's quite a common situation, so I've written my own function for that:

def applyfs(funcs, args):
    """
    Applies several functions to single set of arguments. This function takes
    a list of functions, applies each to given arguments, and returns the list
    of obtained results. For example:

        >>> from operator import add, sub, mul
        >>> list(applyfs([add, sub, mul], (10, 2)))
        [12, 8, 20]

    :param funcs: List of functions.
    :param args:  List or tuple of arguments to apply to each function.
    :return:      List of results, returned by each of `funcs`.
    """
    return map(lambda f: f(*args), funcs)

In your case I would use it the following way:

applyfs([mean, std, var, fxn4 ...], mylist)

Note that you really don't have to use function names (as you would have to do in, for example, PHP4), in Python function is the callable object by itself and can be stored in a list.

EDIT:

Or possibly, it would be more pythonic to use list comprehension instead of map:

results = [f(mylist) for f in [mean, std, var, fxn4 ...]]
like image 91
firegurafiku Avatar answered Oct 02 '22 15:10

firegurafiku