Issue
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
Solution
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]
Answered By - jakub
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.