Tag: natsort

natsort函数的Python模拟(使用“自然顺序”algorithm对列表进行sorting)

我想知道在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'] UPDATE 解决scheme基于此链接 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): […]