如何从外部编写带变量的函数?

Mic*_*ney 4 python scope function definition

我希望你能提供帮助.我正在寻找一种方法来编写一个稍后插入一个项目的函数.让我举个例子:

def general_poly(L):
        """ 
        L, a list of numbers (n0, n1, n2, ... nk)
        Returns a function, which when applied to a value x, returns the value 
        n0 * x^k + n1 * x^(k-1) + ... nk * x^0 
        """
        x = 1
        res = 0
        n = len(L)-1
        for e in range(len(L)):
            res += L[e]*x**n
            n -= 1
        return res
Run Code Online (Sandbox Code Playgroud)

我想我可以在x这里给出一个值,一旦我这样做general_poly(L)(10),它将被替换,x = 10但显然它并不那么容易.我需要更改/添加什么才能使我的功能正常工作?功能如何知道,乘法是x?谢谢你的帮助,伙计们!

ACh*_*ion 8

系统会要求您返回一个函数但返回计算值:

def general_poly(L):
    """ 
    L, a list of numbers (n0, n1, n2, ... nk)
    Returns a function, which when applied to a value x, returns the value 
    n0 * x^k + n1 * x^(k-1) + ... nk * x^0 
    """
    def inner(x):
        res = 0
        n = len(L)-1
        for e in range(len(L)):
            res += L[e]*x**n
            n -= 1
        return res
    return inner
Run Code Online (Sandbox Code Playgroud)

现在general_poly(L)(10)你会做你期望的但是如果你把它分配给一个值可能会更有用,所以可以多次调用它,例如:

L = [...]
fn = general_poly(L)
print(fn(10))
print(fn(3))
Run Code Online (Sandbox Code Playgroud)

你也可以改写inner为:

def general_poly(L):
    return lambda x: sum(e*x**n for n, e in enumerate(reversed(L)))
Run Code Online (Sandbox Code Playgroud)