phpのnatcasesort()と同等の関数がPythonにありますか?
1 に答える
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']
于 2013-01-04T18:37:51.097 に答える