Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting in python - how to sort a list containing alphanumeric values?

I have a list that consists of details like this:

list1 = ["1", "100A", "342B", "2C", "132", "36", "302F"]

now, i want to sort this list, such that the values are in the following order:

list1 = ["1", "2C", "36", "100A", "132", "302F", "342B"]

Just doing list1.sort() obviously doesn't give the correct answer - it gives:

list1 = ["1", "100A", "132", "2C", "36", "302F", "342B"]

I'm assuming this is because python treats all these as strings directly. However, I want to sort them based on their numeric value FIRST, and then the character that follows the number.

How do I proceed?

Thank you so much :)

like image 557
Randomly Named User Avatar asked Oct 14 '13 18:10

Randomly Named User


People also ask

How do you sort a list with letters and numbers in Python?

Summary. Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.

How do you sort alphanumeric strings?

you should split the strings in two first; the other part being the integer part, and the other the string part. then first compare the integers - if the integers are not equal, the string that should appear first is the one with the smaller integer part.


1 Answers

You want to use natural sort:

import re

_nsre = re.compile('([0-9]+)')
def natural_sort_key(s):
    return [int(text) if text.isdigit() else text.lower()
            for text in re.split(_nsre, s)]   

Example usage:

>>> list1 = ["1", "100A", "342B", "2C", "132", "36", "302F"]
>>> list1.sort(key=natural_sort_key)
>>> list1
['1', '2C', '36', '100A', '132', '302F', '342B']

This functions by splitting the elements into lists separating out the numbers and comparing them as integers instead of strings:

>>> natural_sort_key("100A")
['', 100, 'a']
>>> natural_sort_key("342B")
['', 342, 'b']

Note that this only works in Python3 if you are always comparing ints with ints and strings with strings, otherwise you get a TypeError: unorderable types exception.

like image 149
Claudiu Avatar answered Sep 27 '22 20:09

Claudiu