Python 当输入是列表时,如何获取函数的输出

Python 当输入是列表时,如何获取函数的输出,python,arrays,function,evaluation,Python,Arrays,Function,Evaluation,假设我有一个如下的函数: f = (s**2 + 2*s + 5) + 1 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) sum_f = sum (f) Sum_f in my code is the summation of bunch

假设我有一个如下的函数:

f = (s**2 + 2*s + 5) + 1  
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)
sum_f = sum (f)

Sum_f in my code is the summation of bunches of expressions.
其中s为:

s = [1 , 2 , 3]
如何将s传递给我的函数

我知道我可以定义如下函数:

f = (s**2 + 2*s + 5) + 1  
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)
sum_f = sum (f)

Sum_f in my code is the summation of bunches of expressions.
要获得:

fitted_2_dis = [9, 14, 21]

我宁愿不使用这种方法。因为我的实际函数很大,有很多表达式。因此,我没有在代码中引入所有表达式,而是定义了如下函数:

f = (s**2 + 2*s + 5) + 1  
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)
sum_f = sum (f)

Sum_f in my code is the summation of bunches of expressions.
当输入是数组时,是否有其他方法来计算我的函数(sum_f)?
谢谢

列表理解法是一种很好的方法。此外,您还可以使用
映射

fitted_2_dis = list(map(model, s))
如果你是
numpy
粉丝,你可以使用
np.vectorize

np.vectorize(model)(s)
最后,如果将数组转换为
numpy
ndarray
可以直接传入:

import numpy as np

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

列表理解法是一种很好的方法。此外,您还可以使用
映射

fitted_2_dis = list(map(model, s))
如果你是
numpy
粉丝,你可以使用
np.vectorize

np.vectorize(model)(s)
最后,如果将数组转换为
numpy
ndarray
可以直接传入:

import numpy as np

s = np.array(s)
model(s)
功能将很好地完成任务:

>>> map(model, s)
[9, 14, 21]
功能将很好地完成任务:

>>> map(model, s)
[9, 14, 21]
您可以尝试以下方法:

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)
您可以尝试以下方法:

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)

“因此,我没有在我的代码中引入所有表达式,而是像下面这样定义了我的函数”-看起来你根本没有定义函数。@user2357112 sum_f是一些表达式的总和,用s表示”因此,我没有在我的代码中引入所有表达式,而是像下面这样定义了我的函数”-这看起来根本不像你定义的函数。@user2357112总和f是一些表达式在s中的总和