我想知道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']
更新
基于this link解决方案
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);
发布于 2010-06-14 02:11:14
从my answer到Natural Sorting algorithm
import re
def natural_key(string_):
"""See https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/"""
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's comment中的示例。相关:How to reveal Unicodes numeric value property。
在某些语言环境(如'\xb2' ('²') in cp1252 locale on Windows )中,对于Python2上的字节字符串,.isdigit()
也可能失败(返回值不被int()
接受)。
发布于 2013-08-24 13:41:06
您可以在PyPI上查看第三方natsort库:
>>> import natsort
>>> l = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'image3.jpg']
>>> natsort.natsorted(l)
['image1.jpg', 'image3.jpg', 'image12.jpg', 'image15.jpg']
完全公开,我就是作者。
发布于 2012-05-21 21:24:21
在Python2.x和3.x中,此函数可以用作sorted
的key=
参数:
def sortkey_natural(s):
return tuple(int(part) if re.match(r'[0-9]+$', part) else part
for part in re.split(r'([0-9]+)', s))
https://stackoverflow.com/questions/2545532
复制相似问题