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

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

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

Now I am assigned a list of function names that I want to apply in my list.

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

What is the most pythonic way to call these functions?

+5
source share
4 answers

I don’t think there is a pythonic β„’ way to solve this issue. But in my code this is a fairly common situation, so I wrote my own function for myself:

 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 will use it as follows:

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

Note that you really do not need to use function names (as you would need to do, for example, PHP4), in a Python function itself is a callable object and can be stored in a list.

EDIT:

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

 results = [f(mylist) for f in [mean, std, var, fxn4 ...]] 
+6
source

You can get functions by their names:

 map(globals().get, fxnOfInterest) 

And then flip them and apply to the list:

 [func(mylist) for func in map(globals().get, fxnOfInterest)] 
+3
source

You can use eval

 mylist = [1,2,5,4,7,8] fxnOfInterest = ['mean', 'std', 'var', 'fxn6'] for fn in fxnOfInterest: print eval(fn+'(mylist)') 
0
source

Try this example, I think that nothing could be more pythonic than this, I call it a function manager.

 dispatcher={'mean':mean,'std':std,'var':var,'fxn4':fxn4} try: for w in fxnOfInterest : function=dispatcher[w] function(x) except KeyError: raise ValueError('invalid input') 

Each time the function gets a value according to the dictionary dispatcher When you love the Romans in Rome.

0
source

Source: https://habr.com/ru/post/1232374/


All Articles