Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a list in sublists based on the difference between consecutive values

Tags:

python

I have a list with values for which each value has at least one (but often more) consecutive value(s) that have a .033 increment:

l = [26.051, 26.084, 26.117, 26.15, 26.183, 31.146, 31.183, 34.477, 34.51, 34.543]

I would like to split this list into sublists where consecutive items that differ by .033 are combined, and when the difference is larger to start a new sublist:

l = [ [26.051, 26.084, 26.117, 26.15, 26.183], [31.146, 31.183], [34.477, 34.51, 34.543] ] 
like image 480
Jette Avatar asked Jan 01 '23 23:01

Jette


1 Answers

Keep track of the last element you saw and either append the current item to the last sublist, or create a new sublist if the difference is greater than your allowed delta.

res, last = [[]], None
for x in l:
    if last is None or abs(last - x) <= 0.033:
        res[-1].append(x)
    else:
        res.append([x])
    last = x

Note, however, that a value of 0.033 will in fact not return the result that you want, as some of the differences are considerably more (0.037) or just slightly more due to floating point rounding. Instead, you might want to use a slightly more generous value, e.g., using 0.035 gives you [[26.051, 26.084, 26.117, 26.15, 26.183], [31.146], [31.183], [34.477, 34.51, 34.543]]

like image 87
tobias_k Avatar answered Jan 04 '23 11:01

tobias_k