Sorting a list: numbers in ascending, letters in descending

Viewed 3114

This question is actually adapted from one previously asked by Mat.S (image). Although it was deleted, I thought it was a good question, so I am reposting it with clearer requirements and my own solution.


Given a list of letters and numbers, say

['a', 2, 'b', 1, 'c', 3]

The requirement is to sort the numbers in ascending and letters in descending, without altering the relative position of letters and numbers. By this I mean if the unsorted list is:

[L, D, L, L, D]    # L -> letter; # D -> digit 

Then, the sorted list must also be

[L, D, L, L, D] 
  1. The letters and digits do not necessarily alternate in a regular pattern - they can appear in any arbitrary order

  2. After sorting - numbers are ascending, letters are descending.

So for the example above the output is

['c', 1, 'b', 2, 'a', 3]

Another example:

 In[]: [5, 'a', 'x', 3, 6, 'b']
Out[]: [3, 'x', 'b', 5, 6, 'a']

What would be a good way to do this?

6 Answers
Related