Sort a nested list by two items

Let's say I have a list as shown below:

[['Harry', '4'], ['Anthony', '10'], ['Adam', '7'], ['Joe', '6'], ['Ben', '10']] # we can say the first element in it lists is `name`, the second is `score` 

I want to sort it by:

 [['Anthony', '10'], ['Ben', '10'], ['Adam', '7'], ['Joe', '6'], ['Harry', '4']] 

So, first sort it in descending order by count, and then sort it in ascending order by name.


I tried:

 >>> sorted(l, key=lambda x: (int(x[1]), x[0])) [['Harry', '4'], ['Joe', '6'], ['Adam', '7'], ['Anthony', '10'], ['Ben', '10']] 

This works, so now I just need to change it:

 >>> sorted(l, key=lambda x: (int(x[1]), x[0]), reverse=True) [['Ben', '10'], ['Anthony', '10'], ['Adam', '7'], ['Joe', '6'], ['Harry', '4']] 

Ah, reverse=True just changed the list, but did not give the result of the wait. So I just want to change the output of int(x[1]) , but not x[0] .

How can i do this?

+5
source share
1 answer
 >>> sorted(l, key=lambda x: (-int(x[1]), x[0])) [['Anthony', '10'], ['Ben', '10'], ['Adam', '7'], ['Joe', '6'], ['Harry', '4']] 

Basically, by changing the sign of the key evaluation part, the sort keys will be:

 (-10, 'Anthony'), (-10, 'Ben'), (-7, 'Adam'), (-6, 'Joe'), (-4, 'Harry') 

So, with (a, b) < (c, d) <=> (a < c) or (a == c and b < d) you will get the desired sort order.

+6
source

Source: https://habr.com/ru/post/1240270/


All Articles