简体   繁体   中英

how to get the output of a function when the input is a list

Imagine I have a function like below:

f = (s**2 + 2*s + 5) + 1  

where s is :

s = [1 , 2 , 3]

How can I pass the s to my function?

I know that I can define a function like below:

def model(s):
    model = 1 + (s**2 + 2*s + 5)
    return model
fitted_2_dis = [model(value) for value in s]

print ("fitted_2_dis =", fitted_2_dis)

To get :

fitted_2_dis = [9, 14, 21]

I prefer to not using this method. Because my actual function is so big with a lot of expressions. So, instead of bringing all the expressions in my code, I defined my function like below:

sum_f = sum (f)

Sum_f in my code is the summation of bunches of expressions.

Is there any other way to evaluate my function (sum_f) when the input is an array? Thanks

The list comprehension method is a great method. Additionally you may also use map :

fitted_2_dis = list(map(model, s))

If you're a numpy fan you can use np.vectorize :

np.vectorize(model)(s)

Finally if you convert your array to numpy 's ndarray you an pass it in directly:

import numpy as np

s = np.array(s)
model(s)

Map function will fulfill the task quite nicely:

>>> map(model, s)
[9, 14, 21]

You can try this:

import numpy as np


def sum_array(f):
    np_s = np.array(f)
    return (np_s**2 + 2*np_s + 5) + 1

s = [1, 2, 3]
sum_f = sum_array(s)

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