可能重复:
Python是否有内置的字符串自然排序函数?
Python中是否有与PHP的natcasesort()函数等效的函数?
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']
lambdas
是Guido在Python3中考虑删除的一个特性,但幸运的是,其他人说服了他不要这样做。 - abarnert