Howeitzer
Howeitzer

Reputation: 220

How to split an ordered list into a list of lists before the next incidence of a number

I have an ordered list of incremental numbers that range from either 1-4 or 1-6. I would like to create a list of lists whereby they are split before the next incidence of 1.

my_list = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 1, 2, 3 ,4]
list_of_lists = [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4]]

Upvotes: 0

Views: 46

Answers (2)

Riccardo Bucco
Riccardo Bucco

Reputation: 15364

A line is enough:

from itertools import zip_longest

result = [list(range(1, a + 1))
          for a, b in zip_longest(my_list, my_list[1:])
          if b == 1 or b == None]

Upvotes: 1

Sruthi
Sruthi

Reputation: 3018

Iterate through my_list and create sublists everytime you hit a 1.

my_list = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 1, 2, 3 ,4]
result = []
i = 0
while i<len(my_list):
    sub_list = [my_list[i]]
    i+=1
    while i<len(my_list) and my_list[i]>1:
        sub_list.append(my_list[i])
        i+=1
    result.append(sub_list)
print(result) 
# [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4]]

Upvotes: 1

Related Questions