2

A nested list,

A = [[2, 0], [1, 0], [4, 3], [3, 2], [5, 1]] 

I am trying to sort it based on the 1st element in ascending order, i.e

result_A = [[2, 0], [1, 0], [5, 1], [3, 2], [4, 3]]

When the 1st element is common in any of the nested lists, I am trying to sort it based on the 0th element. So,

required_A = [[1, 0], [2, 0], [5, 1], [3, 2], [4, 3]]

This is my code so far:

required_A = sorted(A, key=itemgetter(1))

I am able to sort it based on the 1st element, but am clueless how to sort it again on the 0th element without the remaining order getting messed up. Thanks!

salmanwahed
  • 9,450
  • 7
  • 32
  • 55
quarters
  • 207
  • 1
  • 4
  • 12

2 Answers2

1

This shows how to fix your itemgetter code.

>>> from operator import itemgetter
>>> sorted(A, key=itemgetter(1, 0))
[[1, 0], [2, 0], [5, 1], [3, 2], [4, 3]]

When you pass multiple arguments to itemgetter, it returns a function that can be used to construct a tuple from a given sequence with values from the respective indices that were provided as arguments to itemgetter.

Tuples, like all sequences, can be compared lexicographically in Python. That means they will be compared from left-to-right, index by index, until one sequence overtakes the other. It also means that tuples make excellent keys for your sort.

Shashank
  • 13,713
  • 5
  • 37
  • 63
1

Provided we have items in individual sublists in the reversed order, we can sort the whole list directly. So let's inform the sorted function that we want to consider reversed sublists:

sorted(A, key=lambda x: list(reversed(x))
dlask
  • 8,776
  • 1
  • 26
  • 30