0

this is my first question in stackoverflow. Hope I'm clear.

I would like to transform the following list (sorted ascending by the first element of each item):

[[7, 4], [9, 4], [10, 1]]

into this(sorted descending by the second element of each item, then descending by the first element):

[[9, 4], [7, 4], [10, 1]]

I have tried the sort attribute with no success. Any hint? thks

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Rogelio
  • 3
  • 2
  • What is "the sort attribute"? Is that in a particular programming language? – Stef Jan 14 '22 at 13:37
  • I am trying to code this transformation in Python. I would like to perform a descending sort by the second element of each item of the list, then by the first element. – Rogelio Jan 14 '22 at 13:43
  • Did you read https://docs.python.org/3/howto/sorting.html ? – Stef Jan 14 '22 at 13:45
  • `l = [[7, 4], [9, 4], [10, 1]]` then `l.sort(key=lambda x: (x[1], x[0]), reverse=True)` or alternatively `l.sort(key=lambda x: (-x[1], -x[0]))` or alternatively `from operator import itemgetter; l.sort(key=itemgetter(1,0), reverse=True)` – Stef Jan 14 '22 at 13:47
  • Does this answer your question? [How do I sort a list of dictionaries by a value of the dictionary?](https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary) – JonSG Jan 14 '22 at 13:56
  • yes, I also tried sorted(l,key=lambda x: (x[1], x[0]), reverse=True). It worked too – Rogelio Jan 14 '22 at 16:28

1 Answers1

0

To customize sorting behavior, you can provide the key keyword argument in sorted() or list.sort(). In OP's case, they key argument should be a function that takes in one item in the original list (i.e., a pair of numbers like [7, 4]) and then returns the pair of numbers reversed (i.e., [4, 7]). We need to reverse the sort because by default, the sorted() and list.sort() sort in from smallest to largest.

See more about sorting in python, and in particular the key functions, at https://docs.python.org/3/howto/sorting.html#key-functions.

original = [[7, 4], [9, 4], [10, 1]]
desired = [[9, 4], [7, 4], [10, 1]]

original_sorted = sorted(
    original, 
    key=lambda pair: (pair[1], pair[0]), reverse=True)

original_sorted == desired  # True

The lambda is a function. It is equivalent to the function below. We use a lambda here because it is compact and we do not need to refer to this function anywhere else.

def key_function(pair):
    return pair[1], pair[0]
jkr
  • 17,119
  • 2
  • 42
  • 68