function which is able to return all close values of a list [duplicate]

im trying now for decent time to solve following problem: I have a list of different values, as e.g:

list1 = (17208, 17206, 17203, 17207, 17727, 750, 900, 905)

i want to write a function, which return now all values of this list, which are close to each other for a given correlation length.

So the return in the example should be: res = ([17208,17206,17203,17207],[900,905])

I am already aware of math.isclose(x,y,eps), but i cant apply it to the whole list. If you have any ideas how this function could work like, I would be happy to read about it. Thanks


Solution 1:

You can use this:

list1 = [17208, 17206, 17203, 17207, 17727, 750, 900, 905]

list1.sort()
tmp = [list1[0]]
output = []
for i in range(1,len(list1)):
    if list1[i] - tmp[-1]   < eps:
        tmp.append(list1[i])
    else:
        output.append(tmp)
        tmp = [list1[i]]
output.append(tmp)

# for eps = 10 output is [[750], [900, 905], [17203, 17206, 17207, 17208], [17727]]
print(output)