python-如何在案例中使用间隔创建python的切换案例?

gab*_*f97 1 python switch-statement python-3.x

我是python的新手,我想创建一个switch case,其中case可以将间隔作为条件,例如:

switch = {
    1..<21: do one stuff,
    21...31: do another
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能达到这个结果?

Tom*_*koo 7

就像您已经尝试过的一样,switch在Python 中实现结构的明显方法是使用字典。

为了支持interval,您可以实现自己的dict类:

class Switch(dict):
    def __getitem__(self, item):
        for key in self.keys():                   # iterate over the intervals
            if item in key:                       # if the argument is part of that interval
                return super().__getitem__(key)   # return its associated value
        raise KeyError(item)                      # if not in any interval, raise KeyError
Run Code Online (Sandbox Code Playgroud)

现在您可以使用ranges作为键:

switch = Switch({
    range(1, 21): 'a',
    range(21, 31): 'b'
})
Run Code Online (Sandbox Code Playgroud)

还有一些例子:

>>> print(switch[4])
a

>>> print(switch[21])
b

>>> print(switch[0])
KeyError: 0
Run Code Online (Sandbox Code Playgroud)