Generating (subsetting) list of lists given a min and max in python

Viewed 26

Say I have list:

l = [136.29, 136.67, 136.67, 136.68, 136.38, 136.41, 136.41, 136.43, 136.0, 136.09, 136.1, 136.23, 135.71, 135.9, 135.9, 136.02, 135.73, 135.81, 135.82, 136.19, 135.66, 136.15, 136.16, 136.62, 136.64, 136.66, 135.97, 136.52, 136.52, 136.63, 136.08, 136.48]

where I have set the lower limit/minimum to 136.3 and upper limit/maximum to 136.6.

I am looking to slice list l to find where l[i] falls below the lower limit and where l[i] rises beyond the upper limit. That counts as a cycle. And the next cycle begins when the value is below the lower limit again, and ends as it rises to the upper limit.

From l above, I would like the output to look as follows:

output = [[136.29, 136.67], [136.0, 136.62], [135.97, 136.63]]

1 Answers

You can use a loop, keeping the low value in a temporary variable:

low = 136.3
high = 136.6

out = []
tmp = None
for x in l:
    # wait for first value < low
    if tmp is None:
        if x<low:
            tmp = x
    # once we have the low
    # wait for first value > high
    # append to output, restart cycle
    elif x>high:
        out.append([tmp, x])
        tmp = None

Output:

[[136.29, 136.67],
 [136.0, 136.62],
 [135.97, 136.63]]
Related