简体   繁体   中英

Python numpy array of functions

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM