Python – How to find numbers in a list in numerical order in Python3?

How to find numbers in a list in numerical order in Python3?… here is a solution to the problem.

How to find numbers in a list in numerical order in Python3?

I have a list, like this :

list_1 = [1,2,2,3,1,2]

I want to create another nested list like this :

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

The first nested list consists of only 1s and 2s because, in numerical order, 2 must contain 1 after 1. 3 is not in the first nested list because 1 is followed by 2 instead of 3.

In the second nested list, there are 2 and 3 because 3 comes after 2 and needs to contain 2. 1 does not exist because there is no one after 2.

How can this be implemented in Python 3?

Solution

list_1 = [1,2,2,3,1,2]

m = max(list_1)
print([[i for i in list_1 if i in [j,j+1] ] for j in range(1,m)])

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

#list_1 = [1,2,2,3,1,2,4,2,3,6,5,4]
#->[[1, 2, 2, 1, 2, 2], [2, 2, 3, 2, 2, 3], [3, 4, 3, 4], [4, 5, 4], [6, 5]]

Related Problems and Solutions