Sort list as if it were numbers



Published: 2018-04-14 10:27:34 +0000
Categories: Python,

Language

Python

Description

In BASH you might quite often use sort -n to ensure that strings are sorted as if they were numeric (i.e. so 12a,2a,4a is sorted into the order you'd expect based on the integers at the front).

There isn't a direct way to do this to a list in Python, so you need a wrapper to help implement the functionality

Similar to

  • BASH - sort -n

Based On

Snippet

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

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

    From https://arcpy.wordpress.com/2012/05/11/sorting-alphanumeric-strings-in-python/
    and http://stackoverflow.com/questions/2669059/how-to-sort-alpha-numeric-set-in-python    

    """
    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)

Usage Example

a = ['1a','12a','21c','3b','4a','5a']

print sorted(a)
# ['12a', '1a', '21c', '3b', '4a', '5a']

print sorted_nicely(a)
# ['1a', '3b', '4a', '5a', '12a', '21c']

Keywords

alphanumeric, sorting, strings, sort, number, integer, numeric sort,

Latest Posts

Remotely backing up PFsense Configuration (BASH)
FFMPEG: Converting RMVB to X264 MP4 (BASH)
Recursively print table (print_r equivalent) (LUA)
Bulk Delete Comments from (Self-Hosted) JIRA Issues (Misc)
Add a static entry to the ARP table (BASH)
SSL Cipher Hex codes to Human Readable Names (Misc)
Convert Ascii to Binary (BASH)
Intercepting Outbound DNS Queries (BASH)
Handle Google Verification files within NGinx Configuration (NGinx)
Getting WhatsApp Rich Snippet Previews Working (Misc)

Copyright © 2018 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk and snippets.6zdgh5a5e6zpchdz.onion