web-dev-qa-db-fra.com

Existe-t-il un meilleur moyen d'écrire des instructions imbriquées if en python?

Existe-t-il une manière plus Pythonique de faire des instructions imbriquées if else que celle-ci:

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

Ce script fait partie d'un simple convertisseur.

34
Module_art

J'aime garder le code au sec:

def convert_what_2(numeral_sys_1, numeral_sys_2):
    num_sys = ["Hexadecimal", "Decimal", "Binary"]
    r_value = {0: {1: 1, 2: 2},
               1: {0: 4, 2: 6},
               2: {0: 5, 1: 3} }
    try:
        value = r_value[num_sys.index(numeral_sys_1)][num_sys.index(numeral_sys_2)]
    except KeyError: # Catches when they are equal or undefined
        value = 0
    return value
0
Mikeologist

En utilisant certaines techniques fournies par les autres réponses et en les combinant:

def convert(key1, key2):
    keys = ["Hexadecimal", "Decimal", "Binary"]
    combinations = {(0, 1): 1, (0, 2): 2, (1, 0): 4, (1, 2): 6, (2, 0): 5, (2, 1): 3} # use keys indexes to map to combinations
    try:
        return combinations[(keys.index(key1), keys.index(key2))]
    except (KeyError, ValueError): # if value is not in list, return as 0
        return 0
0
Michael Yang