PHP的natsort函数的Python类似物(使用“自然顺序”算法对列表进行排序)
我想知道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);
-
从我对自然排序算法的回答:
import re def natural_key(string_): """See http://www.codinghorror.com/blog/archives/001018.html""" return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_)]
例:
>>> L = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'image3.jpg'] >>> sorted(L) ['image1.jpg', 'image12.jpg', 'image15.jpg', 'image3.jpg'] >>> sorted(L, key=natural_key) ['image1.jpg', 'image3.jpg', 'image12.jpg', 'image15.jpg']
要支持Unicode字符串,
.isdecimal()
应使用而不是.isdigit()
。请参阅@phihag的注释中的示例。相关:如何显示Unicode
数值属性。.isdigit()int()
在某些语言环境中,Python 2上的字节串也可能会失败(返回值不被接受),例如,在Windows的cp1252语言环境中,该字符串可能会失败(“ \ xb2”(“²”))
。