代码之家  ›  专栏  ›  技术社区  ›  Silver Light

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

  •  20
  • Silver Light  · 技术社区  · 15 年前

    我想知道是否有类似的 PHP natsort 在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']
    

    更新

    解决方案基于 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 回复  |  直到 6 年前
        1
  •  42
  •   Community CDub    8 年前

    my answer Natural 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 .

        2
  •  13
  •   SethMMorton    7 年前

    你可以去看第三方 natsort PYPI上的库:

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

    完全公开,我是作者。

        3
  •  2
  •   phihag    13 年前

    此函数可以用作 key= 的参数 sorted 在python 2.x和3.x中:

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