如何在for循环中定义函数? [英] How can I define functions in a for loop?
问题描述
我试图定义一个3个未知变量(k,m,c)的函数,但是假设我必须定义100次,因为每次都有一个不同的频率f。我可以在python for循环中执行此操作,并将所有函数存储在列表中,以便稍后可以调用它们。
这是我迄今为止
index = -1
f_t = []
for input in [:,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> ],
[<函数_主域__F_分析>],
[函数_主域__F_分析>],
[函数_主域__F_分析>],
[< ;函数__main __。F_analytic>],
...
...
[<函数__main __ .F_analytic>],
[函数_主_F_分析>]
[< function __main __。F_analytic>]]
,错误是: p>
TypeError:'list'对象不可调用
有什么帮助吗?
谢谢!
①尽管你只是想要一个扁平的函数列表,请参阅@BartoszKP的答案。
②您想根据局部变量创建函数。你可以使用lambda表达式,就像@Harsh提出的那样,或者你可以使用默认的变量来实现:
def F_analytic(k ,m,c,f = f):#在这里注意f = f!
F_t = k * m * c * f
return F_t
<应该考虑是否有一个功能列表真的是你想要的(@Wooble已经指出)。
I'm trying to define a function of 3 unknown variables (k,m,c) but let's say I have to define it 100 times due to a different frequency f each time. Can I do this in a for loop in python and store all the functions in a list such that they are callable later?
This is what I have so far
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)
but what I get in turn is a list of functions which are not callable:
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>]]
and the error is:
TypeError: 'list' object is not callable
Any help? Thank you!
① You are nesting lists although you just want a flat list (of functions). See the answer of @BartoszKP on that.
② You want to create functions based on local variables. You can do this using lambdas, as @Harsh is proposing, or you can do it using defaulted variables:
def F_analytic(k, m, c, f=f): # notice the f=f here!
F_t = k*m*c*f
return F_t
③ You should consider whether having a list of functions really is what you want (as @Wooble already pointed out).
这篇关于如何在for循环中定义函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!