python if statement too long and ugly, is there a way to shorten it

This question already has an answer here:

  • Replacements for switch statement in Python? 44 answers

  • 有一个包含给定p的y值的字典

    p={"A":10,.....}
    y=dict[p]
    

    There is no possibility to shorten this piece of code. As you may have noticed, python does not provide any switch-case statement.

    Depending on your usage, you could change it to a dictionary or recalculate it by value:

    values = { "A": 10, "B": 11, "C": 12, "D": 13, "E": 14, "F": 15 }
    y = values[p]
    

    or

    y = ord(p) - ord("A") + 10
    

    Use a dict:

    choice = {
        "A": 10,        
        "B": 11,
        "C": 12,
        "D": 13,
        "E": 14,
        "F": 15
    }[selected]
    

    ie.

    selected = "A"
    choice = {
        "A": 10,        
        "B": 11,
        "C": 12,
        "D": 13,
        "E": 14,
        "F": 15
    }[selected]
    
    print choice
    >>> 10
    

    By immediately adding the [selected] at the end of the dict can easily get a dictionary to behave like a control flow statement. Using this pattern it will always evaluate to the case.

    链接地址: http://www.djcxy.com/p/42756.html

    上一篇: 寻找elif&if的好替代品,就像开关柜一样

    下一篇: python如果语句太长和难看,有没有办法缩短它