Python模擬PHP的natSort函數(shù)(使用“自然順序”算法對列表進行排序)我想知道是否有類似的東西PHP納特排序函數(shù)在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 sdef 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);
添加回答
舉報
0/150
提交
取消