0

I'm trying to write a function that sorts a 2D List with 3 columns and multiple rows: The function first sorts in ascending order by the number in the 3rd column, then with all the elements that have the same "3rd column number", sort them by the 1st column in ascending order.

For example, I have a sample 2d list like:

lst = [[9,3,4],
       [8,4,2],
       [4,2,4]]

After sorting it by the "3rd column" in ascending order first, the list becomes

lst = [[8,4,2],
       [9,3,4],
       [4,2,4]]

Then, sort all rows with the same 3rd column by the "1st column" in ascending order:

lst = [[8,4,2],
       [4,2,4], 
       [9,3,4]]

[4,2,4] was swapped with [9,3,4] because 4 (1st element in the 2nd row of lst) < 9 (1st element in the 3rd row of lst). Also, [4,2,4] and [9,3,4] both have the same 3rd element, which is 4.

How can I write a function to do this without using Numpy? I found an answer similar to my question here, but that is for tuples, not for 2d lists. Does the method for sorting tuples mentioned in the link also work for 2D lists?

Thanks!

TSX
  • 13
  • 5
  • Have you **tried** the solution for tuples? – matszwecja Aug 31 '22 at 14:38
  • Tuples inside a list or lists inside a list doesn't matter. If you have no objection against using the built-in `sorted` or `sort`, follow the description in the linked question for your nested list. – 9769953 Aug 31 '22 at 14:38
  • Your found answer works – Tom McLean Aug 31 '22 at 14:40
  • 2
    Does this answer your question? [Python 3 list sorting with a tie-breaker](https://stackoverflow.com/questions/54300715/python-3-list-sorting-with-a-tie-breaker) – Tom McLean Aug 31 '22 at 14:40
  • 1
    thanks! but will `lst.sort(key=lambda x: (x[2], x[0],x[1]))` do the trick of first sorting it by 3rd element, then 1st, and last 2nd? – TSX Aug 31 '22 at 14:56

0 Answers0