如何对文件进行数字排序? [英] How do you sort files numerically?
问题描述
首先,我发布此内容是因为当我在寻找以下问题的解决方案时,我在stackoverflow上找不到该解决方案.因此,我希望在此处增加一些知识库.
First off, I'm posting this because when I was looking for a solution to the problem below, I could not find one on stackoverflow. So, I'm hoping to add a little bit to the knowledge base here.
我需要处理目录中的某些文件,并且需要对文件进行数字排序.我在 wiki.python中找到了一些有关排序的示例(尤其是使用lambda
模式). org ,我将其放在一起:
I need to process some files in a directory and need the files to be sorted numerically. I found some examples on sorting--specifically with using the lambda
pattern--at wiki.python.org, and I put this together:
#!env/python
import re
tiffFiles = """ayurveda_1.tif
ayurveda_11.tif
ayurveda_13.tif
ayurveda_2.tif
ayurveda_20.tif
ayurveda_22.tif""".split('\n')
numPattern = re.compile('_(\d{1,2})\.', re.IGNORECASE)
tiffFiles.sort(cmp, key=lambda tFile:
int(numPattern.search(tFile).group(1)))
print tiffFiles
我对Python还是很陌生,想问一下社区是否可以对此进行任何改进:缩短代码(删除lambda
),性能,样式/可读性?
I'm still rather new to Python and would like to ask the community if there are any improvements that can be made to this: shortening the code up (removing lambda
), performance, style/readability?
谢谢你, 扎卡里(Jachary)
Thank you, Zachary
推荐答案
这称为自然排序"或人为排序"(与字典排序相反,这是默认设置). 内德B写下了一个简单的版本.
This is called "natural sorting" or "human sorting" (as opposed to lexicographical sorting, which is the default). Ned B wrote up a quick version of one.
import re
def tryint(s):
try:
return int(s)
except:
return s
def alphanum_key(s):
""" Turn a string into a list of string and number chunks.
"z23a" -> ["z", 23, "a"]
"""
return [ tryint(c) for c in re.split('([0-9]+)', s) ]
def sort_nicely(l):
""" Sort the given list in the way that humans expect.
"""
l.sort(key=alphanum_key)
它与您正在执行的操作类似,但可能更笼统.
It's similar to what you're doing, but perhaps a bit more generalized.
这篇关于如何对文件进行数字排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!