问题
I'm new to python, and 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?
回答1:
As it looks like you already tried, the obvious way of implementing a switch
structure in Python is using a dictionary.
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 part of that interval
return super().__getitem__(key) # return its associated value
raise KeyError(item) # if not in any interval, raise KeyError
And now you can use range
s as keys:
switch = Switch({
range(1, 21): 'a',
range(21, 31): 'b'
})
And a few examples:
>>> 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 = {k: v for rng, v in cases.items() for k in rng}
The rest works the same.
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:
- Few long ranges - the first option
- many short ranges - the second option
回答2:
If you really have to use switch/case, then dictionary in python can help you with that. Is there a way for a dictionary key be a range?
This is my take on it :)
def switch_demo(argument):
switcher = {
range(1, 41): "Class 1 (1-40)",
range(41, 50): "Class 2 (41-49)",
range(50, 99): "Class 3 (50-98)",
99: "Class 4 (99)",
100: "Class 5 (100)"
}
for key in switcher:
if type(key) is range and argument in key:
print(switcher[key])
return
elif type(key) is not range and argument == key:
print(switcher[argument])
return
print("Number class not captured")
Hope this helps!
来源:https://stackoverflow.com/questions/57884270/how-to-create-a-switch-case-in-python-with-the-cases-being-intervals