Home > database >  How to sort a python list of arbitrary strings like Excel Column Names?
How to sort a python list of arbitrary strings like Excel Column Names?

Time:05-25

E.g. I have:

x = ["Column a is...", "Column ab uses...", "Column b has..."]

then I need to get:

x = ["Column a is...", "Column b has...", "Column ab uses..."]

CodePudding user response:

If the column identifier is guaranteed to be the second whitespace delimited token in each string then:

x = ["Column a is...", "Column ab uses...", "Column b has..."]

def conv(s):
    n = 0
    for c in reversed(s.split()[1].lower()):
        n *= 26
        n  = ord(c) - ord('a')
    return n

print(sorted(x, key=conv))

The conv() function takes the column identifiers and converts them into a value that can be used for natural sorting

Output:

['Column a is...', 'Column b has...', 'Column ab uses...']
  • Related