python: Piping a value through an if/elif statement

This question already has an answer here:

  • Replacements for switch statement in Python? 44 answers

  • Probably not what you want, but one option is to use a dictionary of functions:

    def do_a();
        ..
    def do_b();
        ..
    def do_c();
        ..
    
    strategy = {
        a: do_a,
        b: do_b
        c: do_c
    }
    
    strategy[f()]()
    

    But normally you'd want some error handling in case the dictionary entry wasn't found, in which case you'd likely end up with a separate variable anyway, plus you now have to extract each case into its own function.

    Maybe even less relevant, if there are only two cases you can use a ternary operator:

    do_a() if f() == a else do_b()
    

    Though likely you already know this, plus your question has more than two cases, plus lots of people don't like the ternary operator, but anyway.

    If you have a language with a switch statement, like C#/Java/C++ etc, or a pattern matching statement, like any of Haskell/OCaml/F#/Scala/Erlang etc, then you can use those. A pattern matching statement looks like this:

    match f() with
    | a ->
        // do something
        // and maybe something else too
    | b ->
        // do some other thing
        // and yet some other thing
    

    but there is no such feature in Python.


    If you only want to map answers (without computing further), then you can solve it with a simple mapping function (similar to junichiro's answer):

    import random
    
    def f():
        foo = ['a', 'b', 'c', 'd', 'e']
        return random.choice(foo)
    
    if __name__ == '__main__':
        from_to = dict(a=2, b=1, c=3, d=4, e=5)
        print(from_to.get(f(), None))
    

    In case you have an unforeseen value from f() then from_to.get(f(), None) would default to None


    There is no way to do this with if/elif and Python does not have a switch statement. You need the temporary variable.

    You can alternatively use a dispatch table if you know the exact values of a, b, and c. It's a little more verbose, but if you have a lot of possible branches, it will be faster and possibly easier to follow.

    To make a dispatch table:

  • Make a function for each branch
  • Make a dictionary that maps a, b, c to their corresponding function
  • Replace all of that code with return DISPATCH_TABLE[f()]()
  • You can find some examples here.

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

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

    下一篇: python:通过if / elif语句管道化一个值