Switch in Python

后端 未结 7 1069
孤独总比滥情好
孤独总比滥情好 2021-01-01 22:34

I have tried making a switch like statement in python, instead of having a lot of if statements.

The code looks like this:

def findStuff(cds):
    L         


        
7条回答
  •  醉梦人生
    2021-01-01 23:33

    You can do something like what you want, but you shouldn't. That said, here's how; you can see how it does not improve things.

    The biggest problem with the way you have it is that Python will evaluate your tests and results once, at the time you declare the dictionary. What you'd have to do instead is make all conditions and the resulting statements functions; this way, evaluation is deferred until you call them. Fortunately there is a way to do this inline for simple functions using the lambda keyword. Secondly, the assignment statement can't be used as a value in Python, so our action functions (which are executed if the corresponding condition function returns a truthy value) have to return a value that will be used to increment c; they can't assign to c themselves.

    Also, the items in a dictionary aren't ordered, so your tests won't necessarily be performed in the order you define them, meaning you probably should use something other than a dictionary that preserves order, such as a tuple or a list. I am assuming you want only ever one case to execute.

    So, here we go:

    def findStuff(cds):
    
        cases = [ (lambda: a[2][0] == 1, lambda: i + 1),
                  (lambda: a[2][1] == 1, lambda: i + 2),
                  (lambda: a[2][2] == 1, lambda: i + 3),
                  (lambda: a[1] == 1,    lambda: L.append(cds[i:i+3], a[0], c) or 0)
                ]
    
        L=[]
        c=0
        for i in range(0, len(cds), 3):
            a=differencesTo(cds[i:i+3])
            for condition, action in cases:
                if condition():
                    c += action()
                    break
        return L
    

    Is this more readable than a sequence of if/elif statements? Nooooooooooooo. In particular, the fourth case is far less comprehensible than it should be because we are having to rely on a function that returns the increment for c to modify a completely different variable, and then we have to figure out how to get it to return a 0 so that c won't actually be modified. Uuuuuugly.

    Don't do this. In fact this code probably won't even run as-is, as I deemed it too ugly to test.

提交回复
热议问题