PHP的Natsort函数的Python类似物(使用“自然顺序”算法对列表进行排序)[重复
题
这个问题在这里已经有一个答案:
- Python是否具有自然弦的内置功能? 16个答案
我想知道是否有类似的东西 PHP NATSORT python的功能?
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的评论. 。有关的: 如何揭示Unicodes数值属性.
.isdigit()
也可能失败(未接受的返回值 int()
)在某些地区的python 2上进行测试,例如 在Windows上的CP1252语言环境中的' xb2'('²').
其他提示
您可以查看第三方 纳特斯特 PYPI的图书馆:
>>> import natsort
>>> l = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'image3.jpg']
>>> natsort.natsorted(l)
['image1.jpg', 'image3.jpg', 'image12.jpg', 'image15.jpg']
全面披露,我是作者。
此功能可以用作 key=
争论 sorted
在Python 2.x和3.x中:
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))
不隶属于 StackOverflow