PHP的natsort函数的Python类似物(使用“自然顺序"算法对列表进行排序) [英] Python analog of PHP's natsort function (sort a list using a "natural order" algorithm)

查看:79
本文介绍了PHP的natsort函数的Python类似物(使用“自然顺序"算法对列表进行排序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有与 PHP natsort 在Python中起作用?

I would like to know if there is something similar to PHP natsort function in 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 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);

推荐答案

来自我的答案自然排序算法:

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的评论.相关:如何显示Unicode数值属性.

To support Unicode strings, .isdecimal() should be used instead of .isdigit(). See example in @phihag's comment. Related: How to reveal Unicodes numeric value property.

.isdigit()在某些语言环境中,例如Python '\ xb2'('²').

.isdigit() may also fail (return value that is not accepted by int()) for a bytestring on Python 2 in some locales e.g., '\xb2' ('²') in cp1252 locale on Windows.

这篇关于PHP的natsort函数的Python类似物(使用“自然顺序"算法对列表进行排序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆