RoadRunner RoadRunner - 5 months ago 6
Python Question

Splitting Nested List at every ['-1']

If I have a nested list like this:

[['01'], ['02'], ['-1'], ['03'], ['04']]


Is there a way I split this nested list at every
['-1']
?

So that it looks like this:

[[['01'], ['02']], [['03'], ['04']]]


Any sort of help would be appreciated :)

Answer

Try this,

lists = [['01'], ['02'], ['-1'], ['03'], ['04'], ['-1'], ['05'], ['-1']]

results = list()
prev_idx = 0
for idx, l in enumerate(lists):
    if l == ['-1']:
        results.append(lists[prev_idx:idx])
        prev_idx = idx+1

if prev_idx <= idx:     # the last group might be [] as shown in this case
    results.append(lists[prev_idx:])

print(results)
# Output
[[['01'], ['02']], [['03'], ['04']], [['05']]]