你如何按数字对文件进行排序? [英] How do you sort files numerically?
本文介绍了你如何按数字对文件进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在处理目录中的一些文件,需要按数字对文件进行排序.我在 找到了一些关于排序的示例——特别是使用 lambda
模式wiki.python.org,我把它放在一起:
I'm processing 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:
import re
file_names = """ayurveda_1.tif
ayurveda_11.tif
ayurveda_13.tif
ayurveda_2.tif
ayurveda_20.tif
ayurveda_22.tif""".split('
')
num_re = re.compile('_(d{1,2}).')
file_names.sort(
key=lambda fname: int(num_re.search(fname).group(1))
)
有没有更好的方法来做到这一点?
Is there a better way to do this?
推荐答案
这称为自然排序"或人工排序"(与字典排序相反,这是默认的排序).Ned 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屋!
查看全文