我想知道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) 我有一个这样的列表:
a = ['1', '3', '02', 'WF2', 'WF5', 'WF01']
Run Code Online (Sandbox Code Playgroud)
我想这样排序:
a = ['1', '02', '3', 'WF01', 'WF2', 'WF5']
Run Code Online (Sandbox Code Playgroud)
使用这样的东西:
def sortby(id):
if 'WF' not in id and id.isdigit():
return int(id)
elif 'WF' in id.upper():
return float('inf')
a.sort(key=sortby)
Run Code Online (Sandbox Code Playgroud)
我可以在没有'WF'前缀的情况下对整数进行排序,但我不知道如何对自己前缀为'WF'的那些进行排序.
我是否需要使用双重排序,即再次排序并仅对前缀为"WF"的排序进行排序,并将-Inf分配给所有其他没有"WF"前缀的条目?任何的想法?
编辑:
def sortby(id):
if 'WF' not in id.upper():
return int(id)
return float('inf')
def sortby2(id):
if 'WF' not in id.upper():
return float('-inf')
return int(id.replace('WF', ''))
a.sort(key=sortby)
a.sort(key=sortby2)
Run Code Online (Sandbox Code Playgroud)
但它不是很好......