简体   繁体   English

在 python 函数中传递和使用动态 arguments

[英]Passing and using dinamically arguments in python functions

I do have a function that receives a list and some parameters, later this function creates a linear equation from the parameters and the list provided.我确实有一个 function 接收一个列表和一些参数,后来这个 function 从参数和提供的列表创建一个线性方程。

def modelFunction(data, a, b, c, offset):
    f = (data[0] * a) + (data[1] * b) + (data[2] * c) + offset
    return f

I would like to create the parameters dinamically and create the linear equation dinamically also.我想动态地创建参数并动态地创建线性方程。 The final objective should be that I can create a different function with a different number of parameters every time I call it.最终的目标应该是我可以创建一个不同的 function,每次调用它时使用不同数量的参数。 Example: If I need to create a linear equation with 2 parameters and it's intercept then it creates a function like:示例:如果我需要创建一个具有 2 个参数的线性方程并且它是截距的,那么它会创建一个 function,例如:

data is a list of len=2数据是 len=2 的列表

def modelFunction(data, a, b,offset):
    f = (data[0] * a) + (data[1] * b) + offset
    return f

If I need to create a linear equation with 3 parameters and it's intercept then it creates a function like:如果我需要创建一个具有 3 个参数的线性方程并且它是截距的,那么它会创建一个 function,例如:

data is a list of len=3数据是 len=3 的列表

def modelFunction(data, a, b, c, offset):
    f = (data[0] * a) + (data[1] * b) + (data[2] * c) + offset
    return f

I believe the * operator might help me but hadn't been able to figure it out我相信 * 运算符可能会帮助我,但无法弄清楚

Equal length checking omitted for brevity:为简洁起见省略了等长检查:

def modelFunction(data, *coeffs):
    return sum(d * c for d, c in zip(data, coeffs)) + coeffs[-1]

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

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