动态if循环(业务逻辑)

时间:2019-02-20 11:19:48

标签: python python-3.x python-2.7 if-statement

我有一个用户输入作为元组列表,其中显示了最小和最大利润以及利润百分比在该范围内,如下元组列表所示:

__importDefault

我做了一个简单的函数来根据该百分比计算利润,如以下代码所示:

args_tuple = (("min1" , 0), ("max1", 10000) , ("percentage1", 0.1),
              ("min2" , 10000) , ("max2", 50000), ("percentage2", 0.05) ,
              ("min3" , 50000), ("max3",100000), ("percentage3",0.1) ,
              ("min4" , 100000), ("max4",None), ("percentage4",0.05))

我现在需要的是,而不是扩展if语句,我只需要一个动态的while循环,以防用户添加def profitCalculator(summed, args_tuple): profit = 0 args_tuple = dict(args_tuple) if args_tuple['min1'] <= summed < args_tuple['max1']: profit += (summed * args_tuple['percentage1']) elif args_tuple['min2'] <= summed < args_tuple['max2']: profit += (args_tuple['min2'] * args_tuple['percentage1']) summed -= args_tuple['min2'] profit += (summed * args_tuple['percentage2']) elif args_tuple['min3'] <= summed < args_tuple['max3']: profit += (args_tuple['min2'] * args_tuple['percentage1']) profit += ((args_tuple['min3'] - args_tuple['min2']) * args_tuple['percentage2']) summed -= args_tuple['min3'] profit += (summed * args_tuple['percentage3']) elif summed >= args_tuple['min4']: profit += (args_tuple['min2'] * args_tuple['percentage1']) profit += ((args_tuple['min3'] - args_tuple['min2']) * args_tuple['percentage2']) profit += ((args_tuple['min3']) * args_tuple['percentage3']) summed -= args_tuple['min4'] profit += (summed * args_tuple['percentage4']) return profit 时,函数中显示的利润计算方式相同。

3 个答案:

答案 0 :(得分:0)

如果更改数据表示,则可以简化算法。 例如,可以使用这样的嵌套列表来代替使用嵌套元组。

args = [[0,10000,0.1],[10000,50000,0.05]]

其中,内部列表中的第一个元素表示最小值,第二最大值和第三百分比。

然后您可以轻松编写一个for循环

for minimum, maximum, profit in (args):
  print(minimum, maximum, profit)

然后使用您的业务逻辑来计算利润


,如果需要索引

for index,(minimum, maximum, profit) in enumerate(args):
  print(index,minimum, maximum, profit)

答案 1 :(得分:0)

更新您的业务逻辑代码将如下

Listener verify.maplistener was not found in the project's classpath

答案 2 :(得分:0)

根据前面的答案,这是一个简短的实现:

args = [[0,10000,0.1],[10000,50000,0.05],[50000,100000,0.1],[100000,200000,0.05]]
def monthlyProfitCalc(summed, args):
    temp = 0
    profit = []
    for index, (minimum, maximum, profitpercent) in enumerate(args):
        if minimum <= summed < maximum:
            profit = [abs(args[x][0] - args[x+1][0])*args[x][2] for x in range(index)]
            temp = sum(temp + i for i in [abs(args[x][0] - args[x+1][0]) for x in range(index)])
            summed -= temp
            profit.append(summed * profitpercent)
    return sum(profit)