I want to sort a list of intervals. Each interval is described by a string using symbols '>='
and '<'
.
However, there are different patterns of intervals:
- some intervals have a lower and upper bound, such as
'>= 0.45 AND < 0.5'
; - some intervals only have the upper or the lower bound, such as
'<0.05'
; - finally, some intervals consists in a single number, such as
'1'
.
Here is an example list to be sorted:
unique_levels = ['1',
'>= 0.45 AND < 0.5',
'>= 0.35 AND < 0.4',
'>= 0.25 AND < 0.3',
'>= 0.85 AND < 0.9',
'>= 0.4 AND < 0.45',
'>= 0.95 AND < 1',
'>= 0.55 AND < 0.6',
'>= 0.3 AND < 0.35',
'>= 0.2 AND < 0.25',
'>= 0.15 AND < 0.2',
'>= 0.5 AND < 0.55',
'>= 0.6 AND < 0.65',
'>= 0.9 AND < 0.95',
'>= 0.8 AND < 0.85',
'>= 0.75 AND < 0.8',
'>= 0.05 AND < 0.1',
'>= 0.65 AND < 0.7',
'>= 0.7 AND < 0.75',
'>= 0.1 AND < 0.15',
'<0.05']
I have tried the following line of code to sort the list:
sorted(unique_levels, key=lambda x: float("".join([i for i in x if i.isdigit()])))
This works for most intervals, but makes a few errors, such as the '1'
being at the start of the sorted list, when it should be at the end.