编程语言
首页 > 编程语言> > PHP的natsort函数的Python模拟(使用“自然顺序”算法对列表进行排序)

PHP的natsort函数的Python模拟(使用“自然顺序”算法对列表进行排序)

作者:互联网

参见英文答案 > Does Python have a built in function for string natural sort?                                    15个
我想知道在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

解决方案基于this link

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);

解决方法:

my answerNatural Sorting algorithm

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_)]

例:

>>> 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()代替.isdigit().参见@phihag’s comment中的示例.相关:How to reveal Unicodes numeric value property.

在某些语言环境(例如‘\xb2’ (‘²’) in cp1252 locale on Windows)中,.isdigit()也可能因Python 2上的字节串而失败(返回值不被int()接受).

标签:python,sorting,natsort
来源: https://codeday.me/bug/20190911/1804095.html