如何创建具有可变参数的Python函数

时间:2013-02-13 00:51:53

标签: python function weighting

我想在Python中创建一个加权函数。但是,加权的数量会有所不同,我需要函数来设置可选参数(例如,您可以找到weightAweightB的费用,但您也可以找到以上所有内容。

基本功能如下:

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?

提前致谢!

5 个答案:

答案 0 :(得分:0)

weightAweightBvolumeAvolumeB参数替换为集合参数。例如:

  • 权重列表和卷列表
  • 列表/一组(重量,体积)元组
  • 具有权重和卷属性的列表/对象集

最后一个例子:

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

答案 1 :(得分:0)

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

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

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)

答案 2 :(得分:0)

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

     # 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)

第二个选项是使用字典

答案 3 :(得分:0)

这可以通过对元组或列表的操作非常简单地完成:

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)

答案 4 :(得分:0)

实际上也有这种方法,最后它与传递列表相同,

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

if __name__ == '__main__':
     weightingfun2(1,2,3,"asdfa")

要了解真实情况的细节,您可以到达那里: http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/

相关问题