Break a list and create lists

Asked

Viewed 52 times

-1

hello! I have the following list in python of numbers:

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

And I want to break that list and create other lists in such a way that it looks like this:

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

I have no idea how to do this operation.

The breaking criterio is always finding the number 1.

  • Add to the question how you tried to address problem and what were the problems faced and error messages. See Stack Overflow Question Checklist.

  • What is the criteria for breaking? When to start a new list?

  • Hello! The criterio for the new list is always find the number 1. Sorry if you got confused, I just realized now.

1 answer

2


Just go through your sequence looking for the value '1' and temporarily accumulating in an auxiliary variable. Whenever you find the value you returns the value of the temporary variable in its generator.

def split(sequence):
    output = []
    for value in sequence:
        if value == '1' and output:
            yield output
            output = []
        output.append(value)
    if output:
        yield output

So, for your entry, we could do:

lista = ['1','2','1','2','3','4','1','2','3','4','5','6','7','1','2','3','4','5','6','7']

for sub_listas in split(lista):
    print(sub_listas)

That the way out will be:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.