python相当于php natcasesort

时间:2013-01-04 18:33:44

标签: python sorting

  

可能重复:
  Does Python have a built in function for string natural sort?

python中的函数是否等同于php的natcasesort()?

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

1 个答案:

答案 0 :(得分:2)

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

标准排序:

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

自然顺序排序(不区分大小写):

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