我想知道 Python 中是否有类似于PHP natsort函数的东西?
l = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'image3.jpg']
l.sort()
给出:
['image1.jpg', 'image12.jpg', 'image15.jpg', 'image3.jpg']
但我想得到:
['image1.jpg', 'image3.jpg', 'image12.jpg', 'image15.jpg']
更新
解决方案基于此链接
def try_int(s):
"Convert to integer if possible."
try: return int(s)
except: return s
def natsort_key(s):
"Used internally to get a tuple by which s is sorted."
import re
return map(try_int, re.findall(r'(\d+|\D+)', s))
def natcmp(a, b):
"Natural string comparison, case sensitive."
return cmp(natsort_key(a), natsort_key(b))
def natcasecmp(a, b):
"Natural string comparison, ignores case."
return natcmp(a.lower(), b.lower())
l.sort(natcasecmp);