elif using dictionary but without excecute the values

This question already has an answer here:

  • Replacements for switch statement in Python? 44 answers

  • def functionA(a1, a2, a3):
        results = {
            'case1': a2 / a3 if a3 != 0.0 else a2,
            'case2': 1,
            # ...
        }
        return results[a1]
    

    However, I would advise against this approach as the entire dictionary has to be computed first only to pick up a single value.

    Instead, if you really want to use dictionaries and have it also efficient, I would suggest:

    myproc = {
        'case1': lambda a2, a3: a2 / a3 if a3 != 0.0 else a2,
        'case2': lambda a2, a3: 1
    }
    

    Then:

    >>> myproc['case1'](2, 3)
    0.6666666666666666
    

    You can use ternary operator inside your dictionary

    def functionA(a1, a2, a3):
    
        results = {
            'case1': a2 if a3==0 else a2/a3,
            'case2': 1
        }
        return results[a1]
    

    Link : https://repl.it/NRkd


    If it's just that one value, you can do it with a simple if-else.

    def functionA(a1, a2, a3):
    
         if a3:
            case1_value = a2/a3
         else: 
            case1_value = a2
    
        results = {
            'case1': case1_value,
            'case2': 1,
            ...
        }
        return results[a1]
    

    Or create a dvision function with this if-else condition and use it in your dict value.

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

    上一篇: 如何在函数中返回多个值(Python)?

    下一篇: elif使用字典,但没有超出值