从我对自然排序算法的回答:
import redef 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']
要支持Unipre字符串,
.isdecimal()应使用而不是
.isdigit()。请参阅@phihag的注释中的示例。相关:如何显示
Unipre数值属性。
.isdigit()int()在某些语言环境中,Python 2上的字节串也可能会失败(返回值不被接受),例如,在Windows的cp1252语言环境中,该字符串可能会失败
(“ xb2”(“²”))。



