PHP 的 natsort 函数的 Python 模拟(使用“自然顺序”算法对列表进行排序)[重复]
- 2025-01-03 08:40:00
- admin 原创
- 115
问题描述:
我想知道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);
解决方案 1:
从我对自然排序算法的回答中:
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()
应使用 而不是。请参阅@phihag 评论.isdigit()
中的示例。相关:如何显示 Unicode 的数值属性。
.isdigit()
`int()`在某些语言环境中,对于 Python 2 中的字节串,也可能失败(返回不接受的值),例如Windows 上 cp1252 语言环境中的 '²' ('²')。
解决方案 2:
您可以在 PyPI 上查看第三方natsort库:
>>> import natsort
>>> l = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'image3.jpg']
>>> natsort.natsorted(l)
['image1.jpg', 'image3.jpg', 'image12.jpg', 'image15.jpg']
坦白说,我就是作者。
解决方案 3:
此函数可用作Python 2.x 和 3.x 中的key=
参数sorted
:
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))
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD