Skip to content
Advertisement

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

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..."]

Advertisement

Answer

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...']
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement