python 按照自然数排序遍历文件 python os.listdir sort by natural sorting
Posted Image Process
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 按照自然数排序遍历文件 python os.listdir sort by natural sorting相关的知识,希望对你有一定的参考价值。
import os import re def sorted_aphanumeric(data): 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(data, key=alphanum_key) file = sorted_aphanumeric(os.listdir("./2")) for f in file: print(f)
参考
https://stackoverflow.com/questions/4813061/non-alphanumeric-list-order-from-os-listdir
Python for whatever reason does not come with a built-in way to have natural sorting (meaning 1, 2, 10 instead of 1, 10, 2), so you have to write it yourself:
import re
def sorted_aphanumeric(data):
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(data, key=alphanum_key)
You can now use this function to sort a list:
dirlist = sorted_aphanumeric(os.listdir(...))
以上是关于python 按照自然数排序遍历文件 python os.listdir sort by natural sorting的主要内容,如果未能解决你的问题,请参考以下文章
Bootstrap Table按照data-formatter的结果排序怎么设置