如何按数字排序文件?
我正在处理一个文件夹里的文件,需要把这些文件按数字顺序排列。我在 wiki.python.org 找到了一些关于排序的例子,特别是使用 lambda
这种写法的例子,然后我把这些例子结合起来了:
import re
file_names = """ayurveda_1.tif
ayurveda_11.tif
ayurveda_13.tif
ayurveda_2.tif
ayurveda_20.tif
ayurveda_22.tif""".split('\n')
num_re = re.compile('_(\d{1,2})\.')
file_names.sort(
key=lambda fname: int(num_re.search(fname).group(1))
)
有没有更好的方法可以做到这一点呢?
6 个回答
6
@April 在 “Python的glob.glob是如何排序的?” 这个问题中提供了一个很好的解决方案,你可以试试看。
#First, get the files:
import glob
import re
files = glob.glob1(img_folder,'*'+output_image_format)
# Sort files according to the digits included in the filename
files = sorted(files, key=lambda x:float(re.findall("(\d+)",x)[0]))
21
只需要这样做:
tiffFiles.sort(key=lambda var:[int(x) if x.isdigit() else x for x in re.findall(r'[^0-9]|[0-9]+', var)])
这样做比使用try/except要快。
70
这叫做“自然排序”或者“人性化排序”,跟默认的字典排序不一样。Ned B 写了一个简单的版本。
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)
它跟你正在做的事情有点像,但可能更通用一些。