Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a sorted list into sub lists when two neighboring value difference is larger than a threshold

Tags:

python

input:

  • a sorted list, like this:[1,2,3,8,10,15,16,17,18,22,23,27,30,31]
  • a threshold, like this: max_diff = 2

expected output:

  • a list of sub lists; each sub list contains the values that the neighboring difference is smaller than max_diff, like this: [[1, 2, 3], [8, 10], [15, 16, 17, 18], [22, 23], [27], [30, 31]]

Here's how I did this, I am wondering if there is a better way to do this.

test_list = [1,2,3,8,10,15,16,17,18,22,23,27,30,31]
max_diff = 2

splited_list = []
temp_list = [test_list[0]]
for i in xrange(1,len(test_list)):
    if test_list[i] - temp_list[-1] > max_diff:
        splited_list.append(temp_list)
        temp_list = [test_list[i]]
    else:
        temp_list.append(test_list[i])        
    if i == len(test_list) -1:
        splited_list.append(temp_list)

print splited_list 
like image 243
Dracarys Avatar asked Aug 25 '15 08:08

Dracarys


1 Answers

You can use enumerate and zip function within a list comprehension to find the indices of the elements that value difference is larger than 2, then split your list based on index list :

>>> li =[1, 2, 3, 8, 10, 15, 16, 17, 18, 22, 23, 27, 30, 31]
>>> inds=[0]+[ind for ind,(i,j) in enumerate(zip(li,li[1:]),1) if j-i>2]+[len(li)+1]
>>> [li[i:j] for i,j in zip(inds,inds[1:])]
[[1, 2, 3], [8, 10], [15, 16, 17, 18], [22, 23], [27], [30, 31]]
like image 68
Mazdak Avatar answered Nov 01 '22 15:11

Mazdak