Home > OS >  Sort list but change the asterisk from being first to last
Sort list but change the asterisk from being first to last

Time:05-31

When sorting a list, I think Python considers '*' as to being "before" (is there a word for what is the order Python uses to sort?) letters and numbers, and I would like it to be the other way. I would like 'A*0' to be after 'A0', 'AB', 'A1', ... rather than being before them. How would one achieve that?

Here is a minimal reproducible example:

list = ["A*0", "A0", "A1", "A*1", "AB", "*BC", "C"]
sorted(list)
Out[7]: ['*BC', 'A*0', 'A*1', 'A0', 'A1', 'AB', 'C']

I would want this behaviour:

list = ["A*0", "A0", "A1", "A*1", "AB", "*BC", "C"]
sorted(list)
Out[7]: ['A0', 'A1', 'AB', 'A*0', 'A*1', "C", "*BC"]

CodePudding user response:

Use the key to sort the existing sorting results again:

>>> lst = ["A*0", "A0", "A1", "A*1", "AB"]
>>> sorted(sorted(lst), key=lambda s: '*' in s)
['A0', 'A1', 'AB', 'A*0', 'A*1']

If you want to get the results at once, you can make the key function generate a tuple:

>>> sorted(lst, key=lambda s: ('*' in s, s))
['A0', 'A1', 'AB', 'A*0', 'A*1']

This may be a little slower (because you need to build tuples), but I think it's easier to understand.

If you don't know enough about the key parameter, you can refer to: key function

CodePudding user response:

Pass a sorting key that replaces * by ~

lst = ["A*0", "A0", "A1", "A*1", "AB"]
# replace * by ~ when sorting (since ~ has the highest ascii value)
sorted(lst, key=lambda x: x.replace('*','~'))
# ['A0', 'A1', 'AB', 'A*0', 'A*1']
  • Related