如何创建一个开关案例,案例是间隔? [英] How to create a switch case with the cases being intervals?

查看:37
本文介绍了如何创建一个开关案例,案例是间隔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个开关/案例,其中案例可以有间隔作为条件,例如:

I'd like to create a switch/case where the cases can have intervals as condition, like:

switch = {
    1..<21: do one stuff,
    21...31: do another
}

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

How can I achieve this result?

推荐答案

在 Python 3.10 中引入了显式 switch 语句 - match.虽然它不支持直接包含检查,所以我们必须利用 保护功能:

In Python 3.10 an explicit switch statement was introduced - match. Although it doesn't support direct containment checking, so we'll have to exploit the guard feature:

number = int(input("num: "))

match number:
    case num if 1 <= num <  21:
        # do stuff
    case num if 21 <= num < 31:
        # do other stuff
    case _:
        # do default

但在这一点上,它引出了一个问题,为什么不使用 if/elif/else 结构......取决于个人喜好.

But at this point it begs the question why not just use an if/elif/else structure... Up to personal taste.

对于早期版本,看起来您已经尝试过,在 Python 中实现 switch 结构的明显方法是使用字典.

For earlier versions, as it looks like you already tried, the obvious way of implementing a switch structure in Python is using a dictionary.

为了支持间隔,你可以实现自己的dict类:

In order to support intervals, you could implement your own dict class:

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

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

And now you can use ranges as keys:

switch = Switch({
    range(1, 21): 'a',
    range(21, 31): 'b'
})

还有几个例子:

>>> print(switch[4])
a

>>> print(switch[21])
b

>>> print(switch[0])
KeyError: 0


另一种选择是解压范围并单独保存范围的每个数字.类似的东西:


Another option is to unpack the ranges and save each number of the range individually. Something like:

cases = {range(1, 21): 'a',
         range(21, 31): 'b'
        }

switch = {num: value for rng, value in cases.items() for num in rng}

其余的工作相同.

两个选项的区别在于第一个节省内存,但是失去了dicts的时间效率(当你检查所有的key),而第二个会保持dict的O(1) 以占用更多内存(所有范围的内容加在一起)为代价的查找.

The difference between the two options is that the first saves memory, but loses the time efficiency of dicts (as you check all the keys), while the second one will maintain the dict's O(1) look-up at the cost of taking more memory (the contents of all ranges together).

根据您的应用程序,您可以在它们之间进行选择,一般来说:

According to your application you can choose between them, as a general rule:

  • 很少有长距离 - 第一个选择
  • 许多短距离 - 第二种选择
  • 介于两者之间 - 为您的案例找到最佳解决方案

这篇关于如何创建一个开关案例,案例是间隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆