Home > database >  How to sort a list of list with the first value, if the both are equal check the second and so on
How to sort a list of list with the first value, if the both are equal check the second and so on

Time:09-19

If you are given a list of list (heterogenous). How do I sort it based on first value and if first value are equal then sort using the second value for those items and even if second values are equal then sort using the third value and so on.

I know how to sort using a particular index of the inner list

Let a list be:

a = [[2,2,1],[2,2,3],[2,1,4],[2,2,5],[1,2,6],[2,2,2]]  

I want:

a=[[1,2,3],[2,1,1],[2,2,2],[2,2,3],[2,2,4],[2,2,5]]

using,

a = sorted(a, key = lambda x:x[0])  

will sort it using the first value, but if the first value is equal then it will add the values according to values which come first.

How do I go about with this?
If on getting the first value equal, I wanted to sort using the last value in the inner list how would I do that?
I mean the output I want is:

a=[[1,2,6],[2,2,1],[2,2,2],[2,2,3],[2,1,4],[2,2,5]]  

How can this be done?

CodePudding user response:

You can create a tuple which defines the order of comparison.

>>> a=[[2,2,1],[2,2,3],[2,1,4],[2,2,5],[1,2,6],[2,2,2]]
>>> sorted(a,key=lambda x: (x[0],x[2],x[1]))
[[1, 2, 6], [2, 2, 1], [2, 2, 2], [2, 2, 3], [2, 1, 4], [2, 2, 5]]

It can also be done using tuple comprehension. For example, sorting only on even indexes:

>>> a=[[2,2,1],[2,2,3],[2,1,4],[2,2,5],[1,2,6],[2,2,2]]
>>> sorted(a,key=lambda x: tuple(x[i] for i in range(len(x)) if i%2==0))
[[1, 2, 6], [2, 2, 1], [2, 2, 2], [2, 2, 3], [2, 1, 4], [2, 2, 5]]

The above sorting example is same as :

>>> a=[[2,2,1],[2,2,3],[2,1,4],[2,2,5],[1,2,6],[2,2,2]]
>>> sorted(a,key=lambda x: (x[0],x[2]))
[[1, 2, 6], [2, 2, 1], [2, 2, 2], [2, 2, 3], [2, 1, 4], [2, 2, 5]]

CodePudding user response:

Literally it sorts with using sorted():

a = [[2,2,1],[2,2,3],[2,1,4],[2,2,5],[1,2,6],[2,2,2]] 
print(sorted(a, key=lambda a: (a[0], a[-1])))
# output - [[1, 2, 6], [2, 2, 1], [2, 2, 2], [2, 2, 3], [2, 1, 4], [2, 2, 5]]

CodePudding user response:

you can just use sorted(a) to sort your list of lists

  • Related