如何在 Python 中使用可变数量的多个参数(例如具有 4 个输入的函数)

问题描述 投票:0回答:1

我想知道如何解决这个问题;我有一个用 4 个输入编写的函数。然而,我需要将此函数应用于 4 个输入的许多不同组合(每次组合的数量都不同),并对输出求和。我将附上我的部分代码,例如,假设我的代码采用参数“chemical”、“acres”、“amountperacre”和“units”。我希望能够一次同时运行多种化学品(链接到以下 3 个变量)的代码,并编写要求和的结果“MTCO2e”,这样我就不必运行代码 50次,记录每次运行的输出,然后将它们全部相加。我该如何解决这个问题/这可能吗?我已经阅读了大量有关多个论点的文章,但在应用我所读的内容时遇到了麻烦/困惑。 现在我的代码(我仍在构建)看起来像这样。它适用于单个化学品,但我不知道如何将其合成为一个可以对 MTCO2e 结果求和的联合代码。谢谢!!

def chemicalemissions(chemical, acres, amountperacre, units):
         .
         .
         defining varibables, etc.
         .
         .
    #Cayuse Plus info
    #density units = lb/gal
    cayuseplusdenisty = 10.26
    activeingredientcayuseplus = .25
    if chemical == 'Cayuse Plus':
        densitykg = cayuseplusdenisty * lbstokg
        #gives density in kg/gal
        if units == 'gal':
            densitykg = densitykg
        #gives density in kg/fl oz
        if units == 'fl oz':
            densitykg = densitykg * galtofloz
        #total kg of product applied
        totalamountappliedkg = densitykg * amountperacre * acres
        #total kg active ingredient
        totalkgactiveingredient = totalamountappliedkg * activeingredientcayuseplus
        #total MJ required
        totalMJ = MJgeneral * totalkgactiveingredient
        #MTCO2e
        MTCO2e = totalMJ * kgCO2perMJperkgactiveingredient * kgCO2etoMTCO2e
        print(MTCO2e)
        
        
    #Tri-Fol info
    #density units = lbs/gal
    trifoldensity = 10.1
    trifolactiveingredient = .25
    if chemical == 'Tri-Fol':
        densitykg = trifoldensity * lbstokg
        #gives density in kg/gal
        if units == 'gal':
            densitykg = densitykg
        #gives density in kg/fl oz
        if units == 'fl oz':
            densitykg = densitykg * galtofloz
        #total kg of product applied
        totalamountappliedkg = densitykg * amountperacre * acres
        #total kg active ingredient
        totalkgactiveingredient = totalamountappliedkg * trifolactiveingredient
        #total MJ required
        totalMJ = MJgeneral * totalkgactiveingredient
        #MTCO2e
        MTCO2e = totalMJ * kgCO2perMJperkgactiveingredient * kgCO2etoMTCO2e

至于我所尝试过的,我已经尝试过 *arg,但似乎这意味着适用于一种变量类型?例如,多个整数。但我不确定我是否可以将其应用于我拥有的变量类型。

python python-3.x arguments
1个回答
0
投票

考虑到您为回应我的评论而提供的上下文,并且如果这不应该是快速而肮脏的,那么最好为这样的化学品创建一个类结构,而不是使用带参数的函数。

您可以这样做:

# define your unit conversion globals
lbstokg = 2.205
galtofloz = 128
# i have no idea what these below are
MJgeneral = 1773
kgCO2perMJperkgactiveingredient = 69
kgCO2etoMTCO2e = 420


class Chemical:  # this is the parent class which contains universal variables
    def __init__(self, name, acres, amountperacre, units):
        self.name = name
        self.acres = acres
        self.amountperacre = amountperacre
        self.units = units

    def get_emissions(self):
        raise NotImplementedError('Can not call this on parent class')


# as each chemical seems to have a different calculation necessary to get the emissions we will make a child class for each chemical

class CayusePlus(Chemical):
    def __init__(self, acres, amountperacre, units):
        name = 'Cayuse Plus'
        super().__init__(name, acres, amountperacre, units)  # this calls the __init__ function as defined in the parent class

        # add unique data for this chemical:
        self.density_in_lbs = 10.26
        self.density_in_kg = self.density_in_lbs * lbstokg
        self.active_ingredient = .25

    def get_emissions(self):
        density_factor = 0
        if self.units == 'gal':
            density_factor = self.density_in_kg
        elif self.units == 'fl oz':
            density_factor = self.density_in_kg * galtofloz

        total_applied = density_factor * self.amountperacre * self.acres
        total_active_ingredient = total_applied * self.active_ingredient
        total_mj = MJgeneral * total_active_ingredient
        return total_mj * kgCO2perMJperkgactiveingredient * kgCO2etoMTCO2e

#-------------------------------------------------------------------------------------------------------------------
# now when you load the data we will create a instance of each class and store them in a list.
# since you said you are coming from excel I have assumed your data will be in csv format.

lines = [('chemical_name_1', 'acres', 'amountperacre', 'units'),
         ('chemical_name_2', 'acres', 'amountperacre', 'units')]
# you did not include how you have your data staged, so I have assumed you have read the file into a list of tuples

chemical_list = []

for line in lines:
    if line[0] == "Cayuse Plus":
        chemical_list.append(CayusePlus(line[1], line[2], line[3]))
    elif line[0] == "Other Chemical":
        chemical_list.append(OtherChemical(line[1], line[2], line[3]))
    # and so on

# now that we have our list made we can just loop though it
MTCO2e_list = []

for chemical in chemical_list:
    MTCO2e = chemical.get_emissions()
    print(f"{chemical.name} - MTCO2e: {MTCO2e}") # note: f strings allow you to easily embed data into a string - you need python3.6 or newer for these to work
    MTCO2e_list.append(float(MTCO2e))

print(f"Sum: {sum(MTCO2e_list)}")

与全部在单个大型函数中相比,这种格式将允许您更轻松地扩展(假设的)报告应用程序的功能。

这只是一个最小的示例 - 有很多方法可以改进此处共享的内容。希望这能为您提供足够的想法来找到更好的解决方案。

如果您只需要一个快速而肮脏的解决方案:只需继续您所做的操作,但不要使用

print(MTCO2e)
结束该功能,而是使用
return MTCO2e
然后在您调用
chemicalemissions()
的循环中,只需将其分配给像
result = chemicalemissions()
这样的变量,然后您可以根据需要操作结果 - 包括将每个结果附加到列表中,然后在您之后
sum()
操作该列表已完成数据循环。

© www.soinside.com 2019 - 2024. All rights reserved.