0

I have a nested list of pairs of numbers:

>>> l = [[0, 0], [1, 3], [3, 2], [3, 4], [4, 6], [5, 2], [3, 1], [1, 6], [5, 4], [4, 3], [2, 5], [3, 0]]

Is it possible to sort the list by the second term and then the first without using packages? The desired output is this:

>>> sort_two_then_one(l)
[[0, 0], [3, 0], [3, 1], [3, 2], [5, 2], [1, 3], [4, 3], [3, 4], [5, 4], [2, 5], [1, 6], [4, 6]]

LogicalX
  • 95
  • 1
  • 10

3 Answers3

1

Here is the answer:

Code

lst = [[0, 0], [1, 3], [3, 2], [3, 4], [4, 6], [5, 2], [3, 1], [1, 6], [5, 4], [4, 3], [2, 5], [3, 0]]

sorted_list = sorted(sorted(lst, key=lambda x: x[0]), key=lambda x: x[1])

print(sorted_list)

Output

[[0, 0],
 [3, 0],
 [3, 1],
 [3, 2],
 [5, 2],
 [1, 3],
 [4, 3],
 [3, 4],
 [5, 4],
 [2, 5],
 [1, 6],
 [4, 6]]
Rahul P
  • 2,493
  • 2
  • 17
  • 31
0

Seems to be a duplicate of Python sorting by multiple criteria

sorted(l, key=lambda x: (x[1], x[0]))
>>> [[0, 0], [3, 0], [3, 1], [3, 2], [5, 2], [1, 3], [4, 3], [3, 4], [5, 4], [2, 5], [1, 6], [4, 6]]
Lydia van Dyke
  • 2,466
  • 3
  • 13
  • 25
0

You can use the optional key argument of sorted() and implement a lambda function. These are all built-in methods of python. See also this

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

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

output

[[0, 0], [3, 0], [3, 1], [3, 2], [5, 2], [1, 3], [4, 3], [3, 4], [5, 4], [2, 5], [4, 6], [1, 6]]

[Program finished]

Björn
  • 1,610
  • 2
  • 17
  • 37