Python自然排序 [英] Python natural sorting

查看:97
本文介绍了Python自然排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些文件需要按名称排序,很遗憾,我不能使用常规排序,因为我也想对字符串中的数字进行排序,因此我进行了一些研究,发现我在寻找什么被称为natural sorting.

I have some files that need to be sorted by name, unfortunately I can't use a regular sort, because I also want to sort the numbers in the string, so I did some research and found that what I am looking for is called natural sorting.

我尝试了给定此处的解决方案,并且有效完美.

I tried the solution given here and it worked perfectly.

但是,对于导致PresserInc-1_10.jpgPresserInc-1_11.jpg这样的字符串导致特定自然键算法失败的字符串,因为它仅与第一个整数匹配,在这种情况下,该整数将为11,因此它将抛出排序.因此,我认为可能会帮助匹配字符串中的所有数字并将它们分组在一起,因此,如果我有PresserInc-1_11.jpg,该算法应该还给我111,所以我的问题是,这可能吗?

However, for strings like PresserInc-1_10.jpg and PresserInc-1_11.jpg which causes that specific natural key algorithm to fail, because it only matches the first integer which in this case would be 1 and 1, and so it throws off the sorting. So what I think might help is to match all numbers in the string and group them together, so if I have PresserInc-1_11.jpg the algorithm should give me 111 back, so my question is, is this possible ?

这是文件名列表:

files = ['PresserInc-1.jpg', 'PresserInc-1_10.jpg', 'PresserInc-1_11.jpg', 'PresserInc-10.jpg', 'PresserInc-2.jpg', 'PresserInc-3.jpg', 'PresserInc-4.jpg', 'PresserInc-5.jpg', 'PresserInc-6.jpg', 'PresserInc-11.jpg']

推荐答案

Google :Python自然排序.

结果1 :您链接到的页面.

但不要到此为止!

结果2 :杰夫·阿特伍德(Jeff Atwood)的博客,其中介绍了如何正确执行操作.

Result 2: Jeff Atwood's blog that explains how to do it properly.

结果3 :我根据Jeff Atwood的博客发布的答案.

Result 3: An answer I posted based on Jeff Atwood's blog.

这是该答案的代码:

import re

def natural_sort(l): 
    convert = lambda text: int(text) if text.isdigit() else text.lower() 
    alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)] 
    return sorted(l, key=alphanum_key)

数据结果:


PresserInc-1.jpg
PresserInc-1_10.jpg
PresserInc-1_11.jpg
PresserInc-2.jpg
PresserInc-3.jpg
etc...

查看其在线运行情况: ideone

See it working online: ideone

这篇关于Python自然排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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