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

时间:2010-03-30 13:29:12

标签: python sorting natsort

我想知道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']

更新

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

3 个答案:

答案 0 :(得分:45)

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

在某些语言环境中,

.isdigit()也可能会失败(返回int()不接受的值)Python 2上的字节串,例如'\xb2' ('²') in cp1252 locale on Windows

答案 1 :(得分:14)

您可以在PyPI上查看第三方natsort库:

>>> import natsort
>>> l = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'image3.jpg']
>>> natsort.natsorted(l)
['image1.jpg', 'image3.jpg', 'image12.jpg', 'image15.jpg']

完全披露,我是作者。

答案 2 :(得分:2)

此函数可用作Python 2.x和3.x中sortedkey=参数:

def sortkey_natural(s):
    return tuple(int(part) if re.match(r'[0-9]+$', part) else part
                for part in re.split(r'([0-9]+)', s))