-1

我正在尝试定义3个未知变量(k,m,c)的函数,但假设我必须定义它100次,因为每次都有不同的频率f。我可以在 python 的 for 循环中执行此操作并将所有函数存储在一个列表中,以便以后可以调用它们吗?

这是我到目前为止所拥有的

index = -1
f_t = []
for f in inputs[:,0]:
   index = index +1
   def F_analytic(k, m, c):
      F_t = k*m*c*f 
      return F_t
   f_t.append([])
   f_t[index].append(F_analytic)

但我得到的是一个不可调用的函数列表:

Out[58]: 
[[<function __main__.F_analytic>],
[<function __main__.F_analytic>],
[<function __main__.F_analytic>],
[<function __main__.F_analytic>],
[<function __main__.F_analytic>],
...
... 
[<function __main__.F_analytic>],
[<function __main__.F_analytic>],
[<function __main__.F_analytic>]]

错误是:

TypeError: 'list' object is not callable

有什么帮助吗?谢谢!

4

5 回答 5

1

① 尽管您只想要一个平面列表(函数),但您正在嵌套列表。请参阅@BartoszKP 的答案。

② 你想创建基于局部变量的函数。您可以使用 lambdas 来做到这一点,正如@Harsh 所提议的那样,或者您可以使用默认变量来做到这一点:

def F_analytic(k, m, c, f=f):  # notice the f=f here!
    F_t = k*m*c*f 
    return F_t

③您应该考虑拥有一个功能列表是否真的是您想要的(正如@Wooble 已经指出的那样)。

于 2013-09-20T11:29:17.467 回答
1

不,您拥有的是一个函数列表,每个内部列表都有 1 个函数。

代替

f_t.append([])
f_t[index].append(F_analytic)

f_t.append(F_analytic)

(虽然老实说,这整个方法似乎相当可疑;有什么理由不想要一个有 4 个参数的函数而不是 100 个有 3 个参数的函数?)

于 2013-09-20T11:23:00.190 回答
0

这是因为您正在创建一个列表列表,您可以像这样调用每个函数对象:

f_t[0][0](1,2,3)

或者,只需创建一个函数列表:

f_t = []

for f in inputs[:,0]:
    index = index +1
    def F_analytic(k, m, c):
        F_t = k*m*c*f 
        return F_t
    f_t.append(F_analytic)

正如其他答案和评论所指出的那样,这一切似乎都是一种相当奇怪的方法。你真的需要这样做吗?:)

于 2013-09-20T11:22:39.700 回答
-1

抱歉,我认为我没有正确回答问题,请尝试以下方法:

f_t = []
for f in input[:,0]:
    f_t.append(lambda k, m, c: k*m*c*f)

您可以通过以下方式轻松调用函数:假设您要调用第一个函数:

f_t[0](k,m,c)

其中 k,m,c 是您的变量

于 2013-09-20T11:47:44.030 回答
-1

让我们清理一下这段代码:

#instead of an index counter, python provide `enumerate`
# so that you can have the counter as part of your loop
#index = -1
f_t = []
for index, f in enumerate(inputs[:,0]):
#   index = index +1
   def F_analytic(k, m, c):
      #these two lines are redundant. You're just returning an expression
      # so this whole function can be a lambda
      F_t = k*m*c*f 
      return F_t
   #why are you creating an inner list for each index position,
   # and then appending the function to it?
   #even if you wanted to have the inner list, you could do it in one step
   f_t.append([])
   f_t[index].append(F_analytic)

如果我们进行指定的更改,我们最终会得到:

f_t = [(lambda k, m, c: k*m*c*f) for f in inputs[:,0]]

当然,更简单的方法是简单地计算乘积的输入,包括f,然后直接相乘。

于 2013-09-20T13:20:18.503 回答