Python: splitting a list of integers based on the step between them

I have the following problem. Having a list of integers, I want to split it into a list of lists when the step between two elements of the original input list is not 1. For example: input = [0, 1, 3, 5, 6, 7], output = [[0, 1 ], [3], [5, 6, 7]]

I wrote the following function, but it was terrible, and I was wondering if any of you guys would be able to get a more pleasant solution. I tried using itertools but could not solve it.

Here is my solution:

def _get_parts(list_of_indices): lv = list_of_indices tuples = zip(lv[:-1], lv[1:]) split_values = [] for i in tuples: if i[1] - i[0] != 1: split_values.append(i[1]) string = '/'.join([str(i) for i in lv]) substrings = [] for i in split_values: part = string.split(str(i)) substrings.append(part[0]) string = string.lstrip(part[0]) substrings.append(string) result = [] for i in substrings: i = i.rstrip('/') result.append([int(n) for n in i.split('/')]) return result 

Thank you so much!

+5
python list split integer
source share
4 answers

It works with any iterable

 >>> from itertools import groupby, count >>> inp = [0, 1, 3, 5, 6, 7] >>> [list(g) for k, g in groupby(inp, key=lambda i,j=count(): i-next(j))] [[0, 1], [3], [5, 6, 7]] 
+7
source share
 def _get_parts(i, step=1): o = [] for x in i: if o and o[-1] and x - step == o[-1][-1]: o[-1].append(x) else: o.append([x]) return o _get_parts([0, 1, 3, 5, 6, 7], step=1) # [[0, 1], [3], [5, 6, 7]]) 
+2
source share

Here is a solution using a for loop.

 def splitbystep(alist): newlist = [[alist[0]]] for i in range(1,len(alist)): if alist[i] - alist[i-1] == 1: newlist[-1].append(alist[i]) else: newlist.append([alist[i]]) return newlist 
0
source share

Here's how I do it:

 inp = [0, 1, 3, 5, 6, 7] base = [] for item in inp: if not base or item - base[-1][-1] != 1: # If base is empty (first item) or diff isn't 1 base.append([item]) # Append a new list containing just one item else: base[-1].append(item) # Otherwise, add current item to the last stored list in base print base # => [[0, 1], [3], [5, 6, 7]] 
0
source share

All Articles