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!
python list split integer
user1863555
source share