Home > Mobile >  Turning a list into a nested list where the next value is 1
Turning a list into a nested list where the next value is 1

Time:05-24

How can I turn a list such as:

data_list = [1,2,3,1,2,3,1,2,3,3,1,2,3,3]

into a list of lists such as:

new_list = [ [1,2,3], [1,2,3], [1,2,3,3], [1,2,3,3] ]

CodePudding user response:

Using a loop:

data = [1,2,3,1,2,3,1,2,3,3,1,2,3,3]
result =[]

for n in data:
    if n == 1 or result == []:
        result.append([])
    result[-1].append(n)

[[1, 2, 3], [1, 2, 3], [1, 2, 3, 3], [1, 2, 3, 3]]

CodePudding user response:

How about a generator like this?

def grouped(it, boundary):
    group = []
    for val in it:
        if val == boundary and group:
            yield group
            group = []
        group.append(val)
    if group:
        yield group

for grp in grouped([1,2,3,1,2,3,1,2,3,3,1,2,3,3], 1):
    print(grp)

Output:

[1, 2, 3]
[1, 2, 3]
[1, 2, 3, 3]
[1, 2, 3, 3]
  • Related