【问题标题】:how to get the output of a function when the input is a list当输入是列表时如何获取函数的输出
【发布时间】:2026-02-08 08:50:01
【问题描述】:

想象一下我有一个像下面这样的函数:

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

其中 s 是:

s = [1 , 2 , 3]

如何将 s 传递给我的函数?

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

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)

获取:

fitted_2_dis = [9, 14, 21]

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

sum_f = sum (f)

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

当输入是一个数组时,还有其他方法可以评估我的函数 (sum_f) 吗? 谢谢

【问题讨论】:

  • “所以,我没有在我的代码中引入所有表达式,而是像下面这样定义了我的函数”——这看起来根本不像你定义了一个函数。
  • @user2357112 sum_f 是一些表达式以 s 为单位的总和

标签: python arrays function evaluation


【解决方案1】:

列表推导方法是一个很好的方法。另外你也可以使用map:

fitted_2_dis = list(map(model, s))

如果您是numpy 的粉丝,您可以使用np.vectorize

np.vectorize(model)(s)

最后,如果您将数组转换为numpyndarray,您可以直接传入:

import numpy as np

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

【讨论】:

    【解决方案2】:

    Map 函数将很好地完成任务:

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

    【讨论】:

      【解决方案3】:

      你可以试试这个:

      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)
      

      【讨论】:

        最近更新 更多