嵌套else-if链的优雅解决方案

时间:2014-09-30 14:38:15

标签: python if-statement nested

在Python中,对于以下嵌套的else-if链是否有更优雅的解决方案?

if interval == 1:
    a += 1
else:
    if interval == 2:
        b += 1
    else:
        if interval == 3:
            c += 1
        else:
            if interval == 4:
                d += 1
            else:
                if interval == 5:
                    e += 1
                else:
                    if interval == 6:
                        f += 1

3 个答案:

答案 0 :(得分:2)

if interval == 1:
    a += 1
elif interval == 2:
    b += 1
elif interval == 3:
    c += 1
elif interval == 4:
    d += 1
elif interval == 5:
    e += 1
elif interval == 6:
    f += 1

当然,如果您可以将a .. f提取到字典中,例如:

state = {"a": 0, "b": 0, "c": 0, "d": 0, "e": 0, "f": 0}

你可以做到

interval_to_state = {1: "a", 2: "b", 3: "c", 4: "d", 5: "e", 6: "f"}
state[interval_to_state[interval]] += 1

答案 1 :(得分:1)

使用list代替多个变量:

#         a  b  c  d  e  f   # Index 0 are unused.
acc = [0, 0, 0, 0, 0, 0, 0]  # OR  [0] * 7
if 1 <= interval <= 7:
    acc[interval] += 1
    # OR acc[interval - 1] += 1
    #    If you don't want to waste a slot in the list.

答案 2 :(得分:0)

我建议使用字典,使用反向查找,就像这样

values = {name: 0 for name in "abcdef"}
indexes = {idx: name for idx, name in enumerate("abcdef", 1)}
values[indexes[interval]] += 1