user9115191
user9115191

Reputation: 33

creating a list of lists based on a condition

I have a list containing some numbers increasing until a certain value, and then somehow repeating the same behavior but nothing periodic. I need to create a list of lists representing these groups from the input.

input:

index=[2,5,6,9,10,11,13,18,19,21, 3,5,8,9,12,17,119, 2,4,6,8,10,12,14,16,18,200, 3,5,7,9,11,14,15,19,233] 

desired_output

[[2, 5, 6, 9, 10, 11, 13, 18, 19, 21],
 [3, 5, 8, 9, 12, 17, 119],
 [2, 4, 6, 8, 10, 12, 14, 16, 18, 200],
 [3, 5, 7, 9, 11, 14, 15, 19, 233]]

I came up with this code but at first I couldn't manage to dump the last iteration to the list_of_lists without explicit intervention. Can you think a better way to do it?

temp_lst=[]
list_of_lists=[]
for i in range(len(index)-1):
    if index[i+1]>index[i]:
        temp_lst.append(index[i])

    else:
        temp_lst.append(index[i])        
        list_of_lists.append(temp_lst)
        temp_lst=[]

list_of_lists.append(temp_lst)
list_of_lists[-1].append(index[-1])

Upvotes: 1

Views: 1688

Answers (1)

blhsing
blhsing

Reputation: 106455

You can append a new sub-list if the output is empty or if the current item is less than the last item in the last sub-list:

list_of_lists=[]
for i in index:
    if not list_of_lists or i < list_of_lists[-1][-1]:
        list_of_lists.append([])
    list_of_lists[-1].append(i)

list_of_lists becomes:

[[2, 5, 6, 9, 10, 11, 13, 18, 19, 21],
 [3, 5, 8, 9, 12, 17, 119],
 [2, 4, 6, 8, 10, 12, 14, 16, 18, 200],
 [3, 5, 7, 9, 11, 14, 15, 19, 233]]

Upvotes: 1

Related Questions