Python中相当于PHP的natcasesort函数

3

1
请参见:https://dev59.com/aG445IYBdhLWcg3we6V9 https://dev59.com/-3E85IYBdhLWcg3w64EA - Lack
是的,这是一个完全相同的问题,并且第一个问题有非常合理的答案——完整的工作实现,以及额外信息的链接。 - abarnert
我正在使用Python 2.7,这里没有lambda。 - Quamis
@Quamis Python 2有lambda表达式。http://docs.python.org/2/reference/expressions.html#lambda - Lack
抱歉,我一直以为这是Python3的功能:D - Quamis
@Quamis:实际上,lambdas是Guido在Python3中考虑删除的一个特性,但幸运的是,其他人说服了他不要这样做。 - abarnert
1个回答

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

标准排序:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接