Sorting alphanumeric strings in Python

In a recent project, I had to sort a list of alphanumeric strings which looked like this:
['AL13, 'AL3', 'AA14', 'AA4']

My first thought was to use the sorted function, and that returned the following result:

>>> sorted(['AL13, 'AL3', 'AA14', 'AA4'])
['AA14', 'AA4', 'AL13', 'AL3']

What I really wanted was it to give me back the list with the numbers sorted in a smarter way:

['AA4', 'AA14', 'AL3', 'AL13']

After searching Stack Overflow, I found this post, which worked perfectly! See Mark Byers variation of Jeff Atwood’s natural sort.

Here’s the source reposted for reference:

import re
def sorted_nicely( l ):
    """ Sorts the given iterable in the way that is expected.

    Required arguments:
    l -- The iterable to be sorted.

    """
    convert = lambda text: int(text) if text.isdigit() else text
    alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
    return sorted(l, key = alphanum_key)
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s