如何使用变量参数创建Python函数

如何使用变量参数创建Python函数,python,function,weighting,Python,Function,Weighting,我想用Python创建一个加权函数。但是,权重的大小不同,我需要该函数具有可选参数(例如,您可以找到weightA和weightB的成本,但您也可以找到上述所有参数 基本功能如下所示: weightA = 1 weightB = 0.5 weightC = 0.33 weightD = 2 cost = 70 volumeA = 100 volumeB = 20 volumeC = 10 volumeD = 5 def weightingfun (cost, weightA, weigh

我想用Python创建一个加权函数。但是,权重的大小不同,我需要该函数具有可选参数(例如,您可以找到
weightA
weightB
的成本,但您也可以找到上述所有参数

基本功能如下所示:

weightA = 1
weightB = 0.5
weightC = 0.33
weightD = 2

cost = 70

volumeA = 100
volumeB = 20
volumeC = 10
volumeD = 5


def weightingfun (cost, weightA, weightB, volumeA, volumeB):
    costvolume = ((cost*(weightA+weightB))/(weightA*volumeA+weightB*volumeB))
    return costvolume
我如何更改函数,例如,我可以对体积C和体积D进行称重


非常感谢!

替换
权重A
权重B
卷A
卷B
参数将用于收集参数。例如:

  • 重量列表和体积列表
  • (重量、体积)元组的列表/集合
  • 具有重量和体积属性的对象列表/集合
最后一个示例:

def weightingfun(cost, objects):
    totalWeight = sum((o.weight for o in objects))
    totalWeightTimesVolume = sum(((o.weight * o.volume) for o in objects))
    costvolume = (cost*totalWeight)/totalWeightTimesVolume
    return costvolume

最好使用具有重量/体积属性的对象(Laurence的帖子)

但要演示如何压缩两个元组:

weights = (1, 0.5, 0.33, 2)
volumes = (100, 20, 10, 5)

def weightingfun(cost, weights, volumes):
    for w,v in zip(weights, volumes):
            print "weight={}, volume={}".format(w, v)

weightingfun(70, weights, volumes)

两个选项:a使用两个列表:

     # option a:
     # make two lists same number of elements
     wt_list=[1,0.5,0.33,2]
     vol_list=[100,20,10,5]

     cost = 70

     def weightingfun (p_cost, p_lst, v_lst):
          a = p_cost * sum(p_lst)
         sub_wt   = 0
         for i in range(0,len(v_lst)):
             sub_wt = sub_wt + (p_lst[i] *  v_lst[i])
         costvolume = a/sub_wt
        return costvolume

     print weightingfun (cost, wt_list, vol_list)

第二种选择是使用字典这可以非常简单地通过元组或列表上的操作来完成:

import operator
def weightingfun(cost, weights, volumes):
    return cost*sum(weights)/sum(map( operator.mul, weights, volumes))

weights = (1, 0.5, 0.33, 2)
volumes = (100, 20, 10, 5)
print weightingfun(70, weights, volumes)

其实也有这个方法,最后跟传递一个列表一样,

def weightingfun2(cost, *args):
    for arg in args:
       print "variable arg:", arg

if __name__ == '__main__':
     weightingfun2(1,2,3,"asdfa")
要了解实际发生的情况,您可以访问:

我也这么想。但是权重和体积的数量会随着时间的推移而变化。还有,如何将正确的权重连接到正确的体积(即权重a*volumeA)?哦,看起来不错。但是我如何创建对象列表/集合?抱歉,我对Python很陌生。使用
[a,b,c]
对于列表,
(a,b,c)
对于元组。非常感谢您的帮助!这非常有效。我使用了@Andrew Alcock函数。我相信其他函数也很好,但这似乎是最简单的方法。