You want an ordered list of strings. Those strings are representations of numbers. Now you want a grouped sorting. First everything that starts with a '9'
, then '8'
and down to '1'
. In each of those groups the values should be sorted in numeric order.
An example list:
a = ['11', '105', '2', '8', '2', '3', '6', '4', '1', '1', '10', '81', '3', '3', '5', '10', '8', '7', '9', '6', '4', '2']
Now let’s do a grouped sorting with a.sort(key=lambda v: v[0])
:
['11', '105', '1', '1', '10', '10', '2', '2', '2', '3', '3', '3', '4', '4', '5', '6', '6', '7', '8', '81', '8', '9']
We see, that the values are grouped now, but we want the values starting with '9'
first. We’re going to fix this by reversing the result with a.sort(key=lambda v: v[0], reversed=True)
['9', '8', '81', '8', '7', '6', '6', '5', '4', '4', '3', '3', '3', '2', '2', '2', '11', '105', '1', '1', '10', '10']
The groups are correct, now we have to sort the values in the groups. So after the sorting according to the first character we have to sort the value by number. That’s easy, we just have to create a tuple
for the key: a.sort(key=lambda v: (v[0], int(v)), reverse=True)
['9', '81', '8', '8', '7', '6', '6', '5', '4', '4', '3', '3', '3', '2', '2', '2', '105', '11', '10', '10', '1', '1']
OK, the values are sorted now, but we have to reverse them in the groups. The easiest way to do that ist to take the negative number: a.sort(key=lambda v: (v[0], -int(v)), reverse=True)
.
['9', '8', '8', '81', '7', '6', '6', '5', '4', '4', '3', '3', '3', '2', '2', '2', '1', '1', '10', '10', '11', '105']
1
solved how to sort python list in a way that if 1 should come before and 10 and 2 before 20