自然分选 [英] Natural sorting

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

问题描述

我有一些文件需要按名称排序,不幸的是我不能使用常规排序,因为我也想对字符串中的数字进行排序,所以我做了一些研究,发现我要找的称为自然排序.

我尝试了这里给出的解决方案,结果完美运行.

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

这是一个文件名列表:

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 的博客,解释了如何正确执行此操作.

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

这是该答案中的代码:

导入重新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)]返回排序(l,key=alphanum_key)

数据结果:

<前>PresserInc-1.jpgPresserInc-1_10.jpgPresserInc-1_11.jpgPresserInc-2.jpgPresserInc-3.jpg等等...

在线查看:ideone

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.

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 ?

Here's a list of filenames:

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 natural sorting.

Result 1: The page you linked to.

But don't stop there!

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

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

Here's the code from that answer:

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)

Results for your data:

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

See it working online: ideone

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

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