如何减少Python中的if语句数量?

2024-05-19 22:10:42 发布

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

我想问一下,我是否可以减少Python中的许多if语句。在我的预算跟踪程序中,我遇到了许多if语句的问题。例如,用户每个月都会收到钱,他每周都有开支,每个月都有经常性开支。但他想展示一天的储蓄。每个if都有很多if语句。如果他想显示一天的储蓄,而其他东西是我需要的月份,我需要将其他东西除以当月的天数,那么我可以计算一天的储蓄(储蓄=收入-支出-经常性支出)。如果你不问我,我想你能理解我。对不起,如果我在这里写错了什么,我的英语不是很好

phases = ['Day','Week','two weeks','three weeks','Month','three months','half a year','Year','two years','five years']
if self.combobox_value_savings == 'Day':
    if self.combobox_value_phase_income == 'Day':
        if self.combobox_value_phase_recurring == 'Day':
            if self.combobox_value_phase_expenses == 'Day':
                # everything the same -> nothing changes
            elif self.combobox_value_phase_expenses == 'Week':
                self.expenses /= 7
            elif self.combobox_value_phase_expenses == 'two weeks':
                self.expenses /= 14
            elif self.combobox_value_phase_expenses == 'three weeks':
                self.expenses /= 21
            # ...

提前谢谢


Tags: selfifvalue语句threeweektwoelif
2条回答

您可以使用下面的逻辑来减少if梯形图(根据您的要求进行更改)

score_map = {'Day':1,'Week':7,'two weeks':14,'three weeks':21,'Month':30}

# 1 option
for i in score_map:
    if self.combobox_value_phase_recurring == i:
        self.expenses /= score_map[i]
#2 option
self.expenses *= score_map.get(self.combobox_value_phase_recurring.lower(), 1)

创建字典映射以减少代码:

dict_mapping = {'Day':1, 'Week': 1/7, 'two weeks':2/7 ,'three_weeks':3/7 } and so on for all the values

phases = ['Day','Week','two weeks','three weeks','Month','three months','half a year','Year','two years','five years']
if self.combobox_value_savings == 'Day':
    if self.combobox_value_phase_income == 'Day':
        if self.combobox_value_phase_recurring == 'Day'
             self.expenses *= dict_mapping[self.combobox_value_phase_recurring]

相关问题 更多 >