Davtho1983
Davtho1983

Reputation: 3954

Split list into sublists by delimiter

I have a list of lists:

[[0, 0], [0, 0], [0, 0], [0, 1, 0], [0, 0]]

I want to split it into what comes before the list [0,1,0] and what comes after like so:

[[0, 0], [0, 0], [0, 0]], [[0, 0]]

If I had a list:

[[0, 0], [0, 0], [0, 0], [0, 1, 0], [0, 0], [0, 1, 0], [0, 0]]

I would want to split it into a list like this:

[[0, 0], [0, 0], [0, 0]], [[0, 0]], [[0, 0]]

I am really stuck with this while loop, which does not seem to reset the temporary list at the right place:

def count_normal_jumps(jumps):
    _temp1 = []
    normal_jumps = []
    jump_index = 0
    while jump_index <= len(jumps) - 1:
        if jumps[jump_index] == [0,0]:
            _temp1.append(jumps[jump_index])
        else:
            normal_jumps.append(_temp1)
            _temp1[:] = []
        jump_index += 1
    return normal_jumps

Why does this not work and is there a better approach?

Upvotes: 2

Views: 131

Answers (2)

blhsing
blhsing

Reputation: 106881

You can use a for loop to append the sublists in the list to the last sublist in a list of lists, and append a new sublist to the list of lists when the input sublist is equal to [0, 1, 0]:

def split(lst):
    output = [[]]
    for l in lst:
        if l == [0, 1, 0]:
            output.append([])
        else:
            output[-1].append(l)
    return output

or you can use itertools.groupby:

from itertools import groupby
def split(lst):
    return [list(g) for k, g in groupby(lst, key=[0, 1, 0].__ne__) if k]

so that:

print(split([[0, 0], [0, 0], [0, 0], [0, 1, 0], [0, 0]]))
print(split([[0, 0], [0, 0], [0, 0], [0, 1, 0], [0, 0], [0, 1, 0], [0, 0]]))

outputs:

[[[0, 0], [0, 0], [0, 0]], [[0, 0]]]
[[[0, 0], [0, 0], [0, 0]], [[0, 0]], [[0, 0]]]

Upvotes: 2

Mark
Mark

Reputation: 5239

You can do something like this:

myList = [[0, 0], [0, 0], [0, 0], [0, 1, 0], [0, 0]]

toMatch = [0, 1, 0]
allMatches = []

currentMatches = []
for lst in myList:
    if lst == toMatch:
        allMatches.append(currentMatches)
        currentMatches = []
    else:
        currentMatches.append(lst)

#push leftovers when end is reached
if currentMatches:
    allMatches.append(currentMatches)

print(allMatches)

Upvotes: 0

Related Questions