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

Mod*_*art 27 python if-statement

有没有比此方法更Python化的方式来嵌套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
Run Code Online (Sandbox Code Playgroud)

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

Ary*_*rez 27

插入所有有效组合到dictionary的tupleS,如果组合不存在,返回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
    }
    return numeral_dict.get((numeral_sys_1, numeral_sys_2), 0)
Run Code Online (Sandbox Code Playgroud)

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

  • 您可以仅使用默认值为0的dict`.get()`方法,而不是`try`语句。 (4认同)
  • 除了KeyError: (2认同)
  • [] 内的括号是多余的。除了空元组之外,是逗号使其成为元组,而不是括号,这只是为了某些情况下的操作顺序。 (2认同)

Sen*_* H. 17

如果您确定没有其他值可以被设置为numeric_sys_1和numeric_sys_2变量,则这是最简单,最干净的解决方案。

另一方面,如果您具有除“十六进制”,“十进制”和“二进制”之外的任何其他值,则必须使用其与可用值的组合来扩展字典。

这里的逻辑是:如果字典键中的变量元组不等于给定的变量元组,则.get()方法将返回“ 0”。如果给定变量元组匹配字典中的任何键,则返回匹配键的值。

def convert_what(numeral_sys_1, numeral_sys_2):
    return {
        ("Hexadecimal", "Decimal") : 1, 
        ("Hexadecimal", "Binary") : 2, 
        ("Binary", "Decimal") : 3,
        ("Decimal", "Hexadecimal") : 4,
        ("Binary", "Hexadecimal") : 5, 
        ("Decimal", "Binary") : 6, 
     }.get((numeral_sys_1, numeral_sys_2), 0)
Run Code Online (Sandbox Code Playgroud)

还有使用发电机可能是一种解决方案。看起来更聪明,但是对于这个简单的要求,硬编码字典比使用生成器要快。


blh*_*ing 8

@Aryerez和@SencerH。的答案起作用时,在列出值对时numeral_sys_1,必须为的每个可能值重复写入的每个可能值numeral_sys_2,这使得在可能值数量增加时难以维护数据结构。您可以改用嵌套的dict代替嵌套的if语句:

mapping = {
    'Hexadecimal': {'Decimal': 1, 'Binary': 2},
    'Binary': {'Decimal': 3, 'Hexadecimal': 5},
    'Decimal': {'Hexadecimal': 4, 'Binary': 6}
}
def convert_what(numeral_sys_1, numeral_sys_2):
    return mapping.get(numeral_sys_1, {}).get(numeral_sys_2, 0)
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用方法生成映射的值对itertools.permutations,其顺序遵循输入序列的顺序:

mapping = dict(zip(permutations(('Hexadecimal', 'Decimal', 'Binary'), r=2), (1, 2, 4, 6, 3, 5)))
def convert_what(numeral_sys_1, numeral_sys_2):
    return mapping.get((numeral_sys_1, numeral_sys_2), 0)
Run Code Online (Sandbox Code Playgroud)