python中复杂的if-elif

时间:2016-12-06 09:00:49

标签: python

我正在尝试在python中创建一个复杂的if else语句。这些语句应检查两个变量。示例代码:

    if value1 == 0.1 and value2 > 2.05:
       value1  = value1 + 0.1
       return value1  
    elif value1  == 0.2 and value2 > 1.85:
       value1  = value1  + 0.1
    elif value1  == 0.3 and value2 > 1.95:
       value1  = value1  + 0.1
    elif value1  == 0.4 and value2 > 2.05:
       value1  = value1  + 0.1
    ...
    if value1 == 0.1 and value2 < 1.75:
       return value1  
    elif value1  == 0.2 and value2 < 1.85:
       value1  = value1  - 0.1
    elif value1  == 0.3 and value2 < 1.95:
       value1  = value1  - 0.1
    elif value1  == 0.4 and value2 < 2.05:
       value1  = value1  - 0.1
    ....

总的来说,每个value1都有一个if或elif,从0.1到1.每次value2都是一个不同的值。我想要做的是检查value2是否小于一个值,以减少value1 = value -1。哪个是最聪明的方法,而不添加许多if -elif语句?

1 个答案:

答案 0 :(得分:4)

如果没有模式,或者它很复杂,以至于不能用循环轻松构建,那么我会做这样的事情:

eq_gt_pairs = ((0.1, 2.05), (0.2, 1.85), (0.3, 1.95), (0.4, 2.05)) # ...

eq_lt_pairs = ((0.1, 1.75), (0.2, 1.85), (0.3, 1.95), (0.4, 2.05)) # ...

for pair in eq_gt_pairs:
    if value1 == pair[0] and value2 > pair[1]:
        return value1 + 0.1

for pair in eq_lt_pairs:
    if value1 == pair[0] and value2 < pair[1]:
        return value1 - 0.1