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


input:

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

expected output:

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

here's how did this, wondering if there better way 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]] 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 == len(test_list) -1:         splited_list.append(temp_list)  print splited_list  

you can use enumerate , zip function within list comprehension find indices of elements value difference larger 2, split list based on index list :

>>> li =[1, 2, 3, 8, 10, 15, 16, 17, 18, 22, 23, 27, 30, 31] >>> inds=[0]+[ind ind,(i,j) in enumerate(zip(li,li[1:]),1) if j-i>2]+[len(li)+1] >>> [li[i:j] i,j in zip(inds,inds[1:])] [[1, 2, 3], [8, 10], [15, 16, 17, 18], [22, 23], [27], [30, 31]] 

Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -