Home > Enterprise >  create sub-list of order integers present in a list and store them in another nested list in python
create sub-list of order integers present in a list and store them in another nested list in python

Time:09-22

I have an array list like this:

list = [1,2,3,4,9,1,12,9,8,7,8,9,10,12,16,1,2,3,4,5,6,7,8,9,10]

I want to create a sub-list from a list of ordered numbers (which are already in sequence in arr_list for e.g. 1,2,3,4 are already in order, similarly 7,8,9,10 and last 10 numbers)

Final output will look like this:

[[1,2,3,4],[7,8,9,10],[1,2,3,4,5,6,7,8,9,10]]

Tried comparing if the i'th element of first for loop is less than the j'th element of second for loop.

This is what i've tried:

sub_list=[]
for i in range(0,length_of_list):
    for j in range(i 1,length_of_list):
        if (arr_list[i] < arr_list[j]):
            sub_list.append(arr_list[i]) 
        else:
            pass

New to python, any leads are much appreciated.

CodePudding user response:

Try this...

res, temp = [], []
lst = [1,2,3,4,9,1,12,9,8,7,8,9,10,12,16,1,2,3,4,5,6,7,8,9,10]
for i in lst:
    if (not temp) or (temp[-1] == i-1):
        temp.append(i)
    else:
        res.append(temp)
        temp = [i]
res.append(temp)
print([i for i in res if len(i)>1])

Outputs:

[[1, 2, 3, 4], [7, 8, 9, 10], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]

tell me if its okay for you...

  • Related