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

Time:12-08

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]]

CodePudding user response:

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]

CodePudding user response:

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]]
  • Related