Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python equivalent to php natcasesort [duplicate]

Tags:

python

sorting

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

like image 906
Quamis Avatar asked Jan 30 '26 11:01

Quamis


1 Answers

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']
like image 99
unutbu Avatar answered Feb 02 '26 04:02

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!