#!/usr/bin/env python import sys from the_semantic_db_code import * from the_semantic_db_functions import * from the_semantic_db_processor import * C = context_list("play with natural sort") # http://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort import re def natural_sort(list, key=lambda s:s): """ Sort the list into natural alphanumeric order. """ def get_alphanum_key_func(key): convert = lambda text: int(text) if text.isdigit() else text return lambda s: [convert(c) for c in re.split('([0-9]+)', key(s))] sort_key = get_alphanum_key_func(key) # list.sort(key=sort_key) return sorted(list,key=sort_key) my_list = ['a1','a12','a13','a','a51','a6','a7','b7','b9','a8','a9','a10','a11','b1','b2','b3','b4'] natural_sort(my_list) print(my_list) sorted_list = natural_sort(my_list) print(sorted_list) sys.exit(0) # buggy. I don't understand why. def natural_sort(l): convert = lambda text: int(text) if text.isdigit() else text.lower() alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] return sorted(l, key = alphanum_key) print(natural_sort['a1','b','c1'])