Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort a 2D list first by 1st column and then by 2nd column

I am trying to find a nice way to sort a 2d list , first by the 1st value , and then by the 2nd value.

I think an example will be the best If I have a list

[[1,4],
[2,7],
[10,1],
[1,2],
[10,6]
[2,1]]

I want that is will be sorted like this

[[1,2],
[1,4],
[2,1],
[2,7],
[10,1],
[10,6]]
like image 861
Oren Avatar asked Jul 30 '14 20:07

Oren


People also ask

How do I sort a 2D list?

To sort a two-dimensional list in Python use the sort() list method, which mutates the list, or the sorted() function, which does not. Set the key parameter for both types using a lambda function and return a tuple of the columns to sort according to the required sort order.

How do you sort a multidimensional list in Python?

Use sorted() with a lambda function to sort a multidimensional list by column. Call sorted(iterable, key=None) with key set to a lambda function of syntax lambda x: x[i] to sort a multidimensional list iterable by the i th element in each inner list x .

How do you sort by first element and then by second element in Python?

Python sort list of tuples by first and second element. To sort the first tuple element we can use an index() method like list[0]. Similar to the second element we can use the list[1] index. By using the sort method we need to sort the lists in place and order.

How do you sort the list of tuples by the second value?

Use the key argument of the sorted() function to sort a list of tuples by the second element, e.g. sorted_list = sorted(list_of_tuples, key=lambda t: t[1]) . The function will return a new list, sorted by the second tuple element.


1 Answers

l=[[1,4],
[2,7],
[10,1],
[1,2],
[10,6],
[2,1]]
print(sorted(l,key=lambda x: (x[0],x[1]))) # use lambda to sort by "x[0]"-> first element of the sublists or x[1] -> second element, if its a tie
[[1, 2], [1, 4], [2, 1], [2, 7], [10, 1], [10, 6]]

Or simply sorted(l) of l.sort() as your elements sort naturally.

A better example would be to sort by the second value only:

print(sorted(l,key=lambda x: (x[1])))
[[10, 1], [2, 1], [1, 2], [1, 4], [10, 6], [2, 7]]
like image 200
Padraic Cunningham Avatar answered Sep 25 '22 06:09

Padraic Cunningham