我正在处理目录中的一些文件,需要对文件进行数字排序。我发现了一些关于排序的例子——特别是使用lambda
模式—在wiki.python.org http://wiki.python.org/moin/HowTo/Sorting,我把它放在一起:
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))
)
有一个更好的方法吗?
这称为“自然排序”或“人工排序”(与默认的字典排序相反)。Ned B 写了一个快速版本。 http://nedbatchelder.com/blog/200712/human_sorting.html
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)
它与您正在做的类似,但可能更普遍一些。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)