-1

我想在 Python 中创建一个加权函数。但是权重的数量会有所不同,我需要该函数具有可选参数(例如,您可以找到 and 的成本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?

提前谢谢!

4

5 回答 5

0

替换weightA, weightB, volumeA,volumeB参数将收集参数。例如:

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

最后一个例子:

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
于 2013-02-13T00:55:49.447 回答
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)
于 2013-02-13T01:10:59.093 回答
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)

第二种选择是使用字典

于 2013-02-13T01:16:54.290 回答
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)
于 2013-02-13T02:17:37.117 回答
0

其实也有这个方法,最后和传一个list是一样的,

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/

于 2013-02-13T03:21:31.337 回答