Reputation: 127
I've been looking for ways to avoid long "for" loops as I'll be dealing with mesh operations and was wondering if there was a way to make an array of functions. Something like the following would be nice.
x=np.array([1,2,3,4,5])
funcs=np.array([func1,func2,func3,func4],dtype=function)
output=funcs(x)
Upvotes: 1
Views: 1766
Reputation: 36249
You can just create a list of functions and then use a list comprehension for evaluating them:
x = np.arange(5) + 1
funcs = [np.min, np.mean, np.std]
output = [f(x) for f in funcs]
If you really think that funcs(x)
reads nicer in your code, you can create a custom class that wraps the above logic:
class Functions:
def __init__(self, *funcs):
self.funcs = funcs
def __call__(self, *args, **kwargs):
return [f(*args, **kwargs) for f in self.funcs]
funcs = Functions(np.min, np.mean, np.std)
output = funcs(x)
Upvotes: 3