The output should be like [[5, 15], [25, 35], [45, 55], [65, 65], [75, 85], [95, 95], [105, 105], [115, 130], [145, 145], [165, 165], [185, 185], [200, 240]]
. like the values have a difference of 5 from 5 to 15 so they would be grouped together with the min and the max. Then between 15 and 25 the difference becomes 10 so the range should break and from 25 to 35 there is a difference of 5 between the values so the range is [25,35] then again the difference becomes 10..... and so on. The values of x would always be in increasing order.
x = [5,10,15,25,30,35,45,50,55,65,75,80,85,95,105,115,120,125,130,145,165,185,200,205,210,215,220,225,230,235,240,500,505]
f = 0
l = 0
b = []
while l < len(x)-1:
current = x[l]
next = x[l 1]
start = x[f]
if next-current == 5:
l =1
else:
b.append([start, current])
f = l 1
l =1
if l 1 == len(x):
b.append([x[f],x[-1]])
print(b)
CodePudding user response:
There's almost certainly a better way to do this but...
def get_group(list_, d):
rv = [list_[0]]
for n in list_[1:]:
if n - rv[-1] > d:
yield [rv[0], rv[-1]]
rv = [n]
else:
rv.append(n)
yield [rv[0], rv[-1]]
x = [5,10,15,25,30,35,45,50,55,65,75,80,85,95,105,115,120,125,130,145,165,185,200,205,210,215,220,225,230,235,240,500,505]
b = [g for g in get_group(x, 5)]
print(b)
Output:
[[5, 15], [25, 35], [45, 55], [65, 65], [75, 85], [95, 95], [105, 105], [115, 130], [145, 145], [165, 165], [185, 185], [200, 240], [500, 505]]
CodePudding user response:
You could use the following logic:
import numpy as np
from scipy.ndimage.interpolation import shift
x = np.array([5,10,15,25,30,35,45,50,55,65,75,80,85,95,105,115,120,125,130,145,165,185,200,205,210,215,220,225,230,235,240,500,505])
x_temp = x[x - shift(x, -1, cval=x[-1] 6) < -5]
x_out, left = [], 0
for i in x_temp:
right = int(np.where(x == i)[0])
x_out.append([x[left], x[right]])
left = int(np.where(x == i)[0]) 1
print(x_out)
----------------------------------------------------------------------------
[[5, 15], [25, 35], [45, 55], [65, 65], [75, 85], [95, 95], [105, 105], [115, 130], [145, 145], [165, 165], [185, 185], [200, 240], [500, 505]]
----------------------------------------------------------------------------
That is, (1) convert your list into an array, (2) find upper bounds of all group, (3) iterate over all upper bounds and create your final list x_out
by simply slicing your input list. That reduces the number of required iterations to the number of existing groups. This solution assumes that your list is sorted. If it is not, you have to sort it first.