Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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...']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading