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] ]
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With