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

2024-09-30 14:15:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用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?你知道吗

谢谢你!你知道吗


Tags: 函数参数数量体积基本功能成本权重cost
3条回答

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

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

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)

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

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)

两个选项: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)

第二种选择是使用字典

相关问题 更多 >

    热门问题