2

I have a list of lists that looks like this [[value, frequency], ... , [value, frequency]]. I wish to sort it in:

  1. descending order by frequency
  2. if two frequencies have the same value then I want to sort those lists in ascending order by value.

Example: [[7,1], [8,2], [4,3], [3,2] --sorted--> [[4,3], [3,2], [8,2], [7,1]]

I've tried sorting the list in descending order by frequency like follows: sorted(list, key=lambda x:x[1], reverse=True) but this doesn't take care of the second condition Appreciate the help!

  • 2
    `key=lambda x: (-x[1], x[0])` – azro Jan 02 '22 at 16:13
  • 2
    Well, as usual, I'm midway through writing an answer and then suddenly the question is closed. I don't know why I bother. None of the answers at the marked duplicate address the problem of sorting **descending** according to one criterion, and **ascending** according according to another. I'm sure there are other duplicates that do address it, but not this one. – Stef Jan 02 '22 at 16:15
  • @Stef You're right, this duplicate doesn't answer the question and the solution given by azro doesn't work either. I've looked at some other duplicates but no luck so far. – Parth Patel Jan 02 '22 at 16:46
  • @ParthPatel What do you mean, "the solution by azro doesn't work either"? It should work. What happens when you try it? – Stef Jan 02 '22 at 17:53
  • @ParthPatel In your question you apparently have a list named `list`. In python that's pretty bad. `list` is already the name of builtin class `list`. Shadowing the name of a builtin is confusing and can have unintended consequences. – Stef Jan 02 '22 at 17:54

0 Answers0