问题描述
我想创建一个开关/案例,其中案例可以有间隔作为条件,例如:
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 语句 - 匹配
.虽然它不支持直接遏制检查,但我们必须利用 守卫功能:
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.
为了支持intervals,你可以实现自己的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
现在您可以使用 range
s 作为键:
And now you can use range
s 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的时间效率(当你检查所有键时),而第二个将保持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:
- 很少的远距离 - 第一个选项
- 许多短距离 - 第二种选择
- 介于两者之间 - 为您的案例找到最佳解决方案
这篇关于如何创建一个案例为间隔的开关案例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!