Split list into several lists at specific values

Viewed 87

I have a list of elements which internally is separated by 0s. The format is like that:

[0, 2, 2, 0, 1, 5, 5, 3, 1, 3, 0, 7, 4, 6, 7, 4, 6]

I would like to use the zeros as separators and split it into sublists. In that example its:

[[], [2, 2], [1, 5, 5, 3, 1, 3], [7, 4, 6, 7, 4, 6]]

The zeros will therefore disappear. A leading zero or an ending zero should make an empty list at the beginning or the end.

Until know, I do that in an ugly way by joining the list together to a string, then split it and make a list of it again.

Is there a fancy pythonic way to do that easier?

3 Answers

You could use a groupby approach:

from itertools import groupby
k = [0, 2, 2, 0, 1, 5, 5, 3, 1, 3, 0, 7, 4, 6, 7, 4, 6]

gr = groupby(k, lambda a: a==0)

l = [[] if a else [*b] for a,b in gr]

print(l)

Output:

[[], [2, 2], [], [1, 5, 5, 3, 1, 3], [], [7, 4, 6, 7, 4, 6]]

You can fix the internal [] by:

l = [ a for idx,a in enumerate(l) if idx in (0,len(l)) or a]

to get

[[], [2, 2], [1, 5, 5, 3, 1, 3], [7, 4, 6, 7, 4, 6]]

You can substitute the list comp by

l = []
for a,b in gr:
    if a: 
        l.append([])
    else: 
        l.append([*b])

You can solve this problem using this solution: Python split list at zeros

from itertools import groupby

def split_a_list_at_zeros(L):
    return [list(g) for k, g in groupby(L, key=lambda x:x!=0) if k]

list1 = [0, 2, 2, 0, 1, 5, 5, 3, 1, 3, 0, 7, 4, 6, 7, 4, 6]

new_list = split_a_list_at_zeros(list1)

print(new_list) # [[2, 2], [1, 5, 5, 3, 1, 3], [7, 4, 6, 7, 4, 6]]

You can use this:

def func(arr):
    indices = [-1] + [i for i in range(len(arr)) if arr[i] == 0] + [len(arr)]
    return [arr[indices[i] + 1 : indices[i + 1]] for i in range(len(indices) - 1)]
Related