有没有更好的方法在python中编写嵌套的if语句?

188 阅读1分钟
有比此方法更多的pythonic方法来嵌套if语句:

def convert_what(numeral_sys_1, numeral_sys_2):

    if numeral_sys_1 == numeral_sys_2:      
        return 0
    elif numeral_sys_1 == "Hexadecimal":
        if numeral_sys_2 == "Decimal":
            return 1
        elif numeral_sys_2 == "Binary":
            return 2
    elif numeral_sys_1 == "Decimal":
        if numeral_sys_2 == "Hexadecimal":
            return 4
        elif numeral_sys_2 == "Binary":
            return 6
    elif numeral_sys_1 == "Binary":
        if numeral_sys_2 == "Hexadecimal":
            return 5
        elif numeral_sys_2 == "Decimal":
            return 3
    else:
        return 0

该脚本是简单转换器的一部分。

Answer:

将所有有效组合插入到元组字典中,如果组合不存在,则返回0:


def convert_what(numeral_sys_1, numeral_sys_2):
    numeral_dict = {("Hexadecimal", "Decimal") : 1, ("Hexadecimal", "Binary") : 2, ("Decimal", "Hexadecimal") : 4, 
                       ("Decimal", "Binary") : 6, ("Binary", "Hexadecimal") : 5, ("Binary", "Decimal") : 3}
    try:
        return numeral_dict[numeral_sys_1, numeral_sys_2]
    except KeyError:
        return 0

如果您打算循环使用该函数,最好在函数外部定义字典,这样就不会在每次调用该函数时都重新创建它。