How to create a switch case in python with the cases being intervals?
问题 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