how to naturally sort a list that contains simillar values

59 Views Asked by At

i have a list of strings like this: ['id:9', 'vector:1', 'table:1', 'product:10', 'number:3', 'Number:4']

i want to sort it from higher integer value to lower and then the rest: ['product:10', 'id:9', 'Number:4', 'number:3', 'vector:1', 'table:1']

the values are all integer without including 0, the string that are attached to them can be all lower case, all upper case, part lower case, part upper case, while also being similar to another item: Number, NUMBER, number, NUMber

i tried using natsort but that didn't arrange them correctly, also i tried some other solutions discussed here still didn't work in my case, so how can this be done in python?

1

There are 1 best solutions below

0
Jamie Deith On

If you create a function converting each string to a tuple you can then sort on those tuples:

l = ['id:9', 'vector:1', 'table:1', 'product:10', 'number:3', 'Number:4']

def negative_num_then_name(s):
    name, num_str = s.split(':')
    return -int(num_str), name

l.sort(key=negative_num_then_name)
l

['product:10', 'id:9', 'Number:4', 'number:3', 'table:1', 'vector:1']

If you want to understand what's going on under the covers, this shows you what is actually being sorted (in ascending order):

l = ['id:9', 'vector:1', 'table:1', 'product:10', 'number:3', 'Number:4']
[negative_num_then_name(elem) for elem in l]

[(-9, 'id'),
 (-1, 'vector'),
 (-1, 'table'),
 (-10, 'product'),
 (-3, 'number'),
 (-4, 'Number')]

sort looks first to the first element of each tuple - the integer - and only in the case of a tie it then looks to the second element - the string.