3

Possible Duplicate:
Does Python have a built in function for string natural sort?

Is there a function in python equivalent to php's natcasesort()?

http://php.net/manual/en/function.natcasesort.php

Community
  • 1
  • 1
Quamis
  • 10,924
  • 12
  • 50
  • 66
  • 1
    See: http://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort http://stackoverflow.com/questions/2545532/python-analog-of-natsort-function-sort-a-list-using-a-natural-order-algorithm – Lack Jan 04 '13 at 18:36
  • Yes, this is an exact dup, and the first question has perfectly reasonable answers—complete working implementations, links to additional information. – abarnert Jan 04 '13 at 18:44
  • i'm using python 2.7, no lambda's here – Quamis Jan 04 '13 at 18:50
  • @Quamis Python 2 has lambdas. http://docs.python.org/2/reference/expressions.html#lambda – Lack Jan 04 '13 at 18:54
  • sorry, I always thought its a python3 feature:D – Quamis Jan 04 '13 at 19:15
  • @Quamis: Actually, `lambdas` are a feature Guido _thought about removing_ in python3, but fortunately everyone else talked him out of it. – abarnert Jan 04 '13 at 20:01

1 Answers1

3
import re

def atoi(text):
    return int(text) if text.isdigit() else text.lower()

def natural_keys(text):
    '''
    alist.sort(key=natural_keys) sorts in human order
    http://nedbatchelder.com/blog/200712/human_sorting.html
    (See Toothy's implementation in the comments)
    '''    
    return [ atoi(c) for c in re.split('(\d+)', text) ]

names = ('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png')

Standard sorting:

print(sorted(names))
# ['IMG0.png', 'IMG3.png', 'img1.png', 'img10.png', 'img12.png', 'img2.png']

Natural order sorting (case-insensitive):

print(sorted(names, key = natural_keys))
# ['IMG0.png', 'img1.png', 'img2.png', 'IMG3.png', 'img10.png', 'img12.png']
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677