我想在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?
提前致谢!
答案 0 :(得分: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
答案 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/