简体   繁体   English

在python中循环定义几个函数并相应地分配它们

[英]defining several functions in a loop and assigning them accordingly, in python

For defining several functions in a loop I have no problem using the code: 为了在循环中定义几个函数,我使用代码没有问题:

U=[]
for i in range(100):
    U.append(function('U_%s' %i, x))

but if I want to also assign some rules to these functions, again from within a loop, then I don't know how to accomplish this, always receiving errors like these: " SyntaxError: can't assign to operator ", " SyntaxError: can't assign to function call ", " TypeError: 'list' object is not callable " and etc. depending on how that I have so far tried to assign to the functions in a loop. 但是,如果我也想再次从循环内为这些功能分配一些规则,那么我不知道如何实现,总是会收到如下错误:“ SyntaxError:无法分配给运算符 ”,“ SyntaxError:不能分配给函数调用 “,” TypeError:'列表'对象不可调用 “等,这取决于到目前为止我在循环中尝试分配给函数的方式。 I want to assign a power series in x to each function with the coefficients of the power series being different for different functions. 我想将x的幂级数分配给每个函数,幂函数的系数对于不同的函数是不同的。

Any idea how to resolve this? 任何想法如何解决这个问题? Regards 问候

How about this: 这个怎么样:

U=[]
for i in range(100):
    coeffs = (1, 2, 3)
    def func(x):
        return coeffs[0] + x*coeffs[1] + x*x*coeffs[2]
    U.append(func)

This is just to share my practice. 这只是分享我的做法。 The below works fine. 以下工作正常。

def func(x):
    ''''''
    coeffs = (1, 2, 3)
    return coeffs[0] + x*coeffs[1] + x*x*coeffs[2]

def main():
    ''''''
    U=[]
    for i in range(100):
        U.append(func(i))
    print U

if __name__ == "__main__":
    main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM