Sil*_*ght 22 python sorting natsort
我想知道Python中是否有类似PHP natsort函数的东西?
l = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'image3.jpg']
l.sort()
Run Code Online (Sandbox Code Playgroud)
得到:
['image1.jpg', 'image12.jpg', 'image15.jpg', 'image3.jpg']
Run Code Online (Sandbox Code Playgroud)
但我想得到:
['image1.jpg', 'image3.jpg', 'image12.jpg', 'image15.jpg']
Run Code Online (Sandbox Code Playgroud)
UPDATE
解决方案基于此链接
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);
Run Code Online (Sandbox Code Playgroud)
jfs*_*jfs 45
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_)]
Run Code Online (Sandbox Code Playgroud)
例:
>>> 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']
Run Code Online (Sandbox Code Playgroud)
要支持Unicode字符串,.isdecimal()应该使用而不是.isdigit().请参阅@ phihag的评论中的示例.相关:如何显示Unicodes数值属性.
.isdigit()int()在某些语言环境中,Python 2上的字节字符串也可能失败(返回值不被接受),例如,Windows上的cp1252语言环境中的'\ xb2'('²').
Set*_*ton 15
您可以在PyPI上查看第三方natsort库:
>>> import natsort
>>> l = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'image3.jpg']
>>> natsort.natsorted(l)
['image1.jpg', 'image3.jpg', 'image12.jpg', 'image15.jpg']
Run Code Online (Sandbox Code Playgroud)
完全披露,我是作者.
| 归档时间: |
|
| 查看次数: |
16378 次 |
| 最近记录: |