Maybe this question has been asked before, but I couldn’t find it.
I am trying to implement something that determines what range a given value is in. In this example, x may be any real number.
def f(x):
if x < 0.1:
do_something_1()
elif 0.1 <= x < 1:
do_something_2()
elif 1 <= x < 10:
do_something_3()
elif x >= 10:
do_something_4()
…you get the idea.
I’ve seen plenty of examples of dictionaries replacing switch statements in Python, but I’ve always understood dictionaries as indexing discrete values.
I find it hard to believe that the if-elif-else chain is the best solution in this situation. Does anyone know of a better one?
Use the bisect package to find the index where the value lies, and then call the appropriate function. In your example: