Search code examples
pythonsortingalphanumeric

Trying to sort alphanumeric coordinates


I have a list of coordinates and I want to sort them by the numbers that are inbetween text and symbols.

coords = ['`154blue', '`155blue', 'a154blue', 'a155blue', 'b154blue', 'b155blue', 'c154blue', 'c155blue', 'd154blue', 'd155blue', 'e155blue', '`156brown', 'a156brown', 'a158brown', 'b150brown']

I would want it to be listed like this:

coords = ['b150brown','`154blue', 'a154blue', 'b154blue', 'c154blue','d154blue','`155blue', 'a155blue', 'b155blue', 'c155blue', 'd155blue', 'e155blue', '`156brown', 'a156brown', 'a158brown']

I have tried different sorting and lambda sorting but I cant get it to do it by the numbers.


Solution

  • You can use a regular expression to obtain the number, and sort first on that then by the underlying string say if there are two coords with the same number:

    import re
    
    coords = ['`154blue', '`155blue', 'a154blue', 'a155blue', 'b154blue', 'b155blue', 'c154blue', 'c155blue', 'd154blue', 'd155blue', 'e155blue', '`156brown', 'a156brown', 'a158brown', 'b150brown']
    coords.sort(key=lambda c: (re.search(r'\d+', c).group(0), c))
    print(coords)
    

    Output:

    ['b150brown', '`154blue', 'a154blue', 'b154blue', 'c154blue', 'd154blue', '`155blue', 'a155blue', 'b155blue', 'c155blue', 'd155blue', 'e155blue', '`156brown', 'a156brown', 'a158brown']