Python if, elif, else chain alternitive

This question already has an answer here:

  • Replacements for switch statement in Python? 44 answers

  • Try using a dictionary setting in which the key is the value that you are testing for and the entry for that key is a function to process. Some of the text books on Python point out that this is a more elegant solution than a series of if ... elif statements and picks up the entry immediately instead of having to test each possibility. Note that since each key can be of any type, this is better than something like the switch statement in C which requires the switch argument and the cases to be integer values. For example.

    def default(command)
        print command, ' is an invalid entry'
    
    mydict = {'create':mycreate, 'delete':mydelete, 'update':myupdate}
    
    action = mydict.get(command, default)
    # set up args from the dictionary or as command for the default.
    action(*args)
    

    An interesting point is that Most efficient way of making an if-elif-elif-else statement when the else is done the most? states that while the get is more "elegant" it may actually be slower than the code below. However, that may be because the post deals with direct operations and not function calls. YMMV

    def default(command)
        print command, ' is an invalid entry'
    
    mydict = {'create':mycreate, 'delete':mydelete, 'update':myupdate}
    
    if command in mydict:
        action = mydict.[command]
        # set up args from the dictionary .
        action(*args)
    else:
        default(command)
    
    链接地址: http://www.djcxy.com/p/42766.html

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

    下一篇: Python if,elif,else链交替