Python Forum
sorting alphanumeric values in a human way - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: sorting alphanumeric values in a human way (/thread-32133.html)



sorting alphanumeric values in a human way - idiotonboarding - Jan-22-2021

So simple question, I could make it work in a lambda probably but my experience is limited and I suspect there may already be a built in to do what I need. I have some data that I currently sort using sort like so

data.sort(order=['bin','ref'])

I'm not the one who uses the data, so i am only just finding out it only really works 80% of the time. 'bin' is always an integer, so the sort works great, and that's the critical value. sorting by ref is where it breaks down, as 'ref' is alphanumeric which leaves us to a bad order. ref values are of the format 'A1', 'A4', 'A13', which means when sorted 'A13' comes before 'A4', which is not the desired behavior. is there a built in sort option to do a windows style alphabetic sort, instead of a linux style? or do i need to manually mangle the string and split and sort it that way?

I always prefer to use a built in w/ options than roll my own, because one will always be less buggy than the other, and it's not my code lol


RE: sorting alphanumeric values in a human way - bowlofred - Jan-22-2021

Python sort doesn't have an order keyword, so I don't understand how this is working for you. Can you include some sample data and show the correct order you want from it? I can interpret "integer" as meaning either a python int or a python str that encodes an integer. Which one is your data?


RE: sorting alphanumeric values in a human way - BashBedlam - Jan-22-2021

Here's one option :

from itertools import groupby

def keyfunction (string) :
	return [int (''.join (group)) if key else ''.join (group) for key, group in groupby (string, str.isdigit)]

test_list = ['A35','A4', 'B3', 'A1', 'A15']

print (sorted (test_list, key = keyfunction)) 
If you can and want to install natsort with pip, here's another option :

import natsort

test_list = ['A35','A4', 'B3', 'A1', 'A15']
print (natsort.natsorted (test_list))



RE: sorting alphanumeric values in a human way - idiotonboarding - Jan-22-2021

oh sorry! I confused myself, it is a numpy array (a named array i guess) so I am sorting it by the two named columns. I often use terms incorrectly with these arrays so hopefully I am using it correctly here. the entirety of my sort code is as I said above:
def sort_by_column(data, order=['bin','ref']):
    '''sort data in place based on order list'''

    data.sort(order=order)
'bin' is an actual integer and it sorts it fine by that, it's the second ranking that is sorting, but not sorting the way i want. Does that clarify?


https://numpy.org/doc/stable/reference/generated/numpy.ndarray.sort.html