首页 > 编程语言 > 详细

python 按照自然数排序遍历文件 python os.listdir sort by natural sorting

时间:2018-09-06 12:04:59      阅读:329      评论:0      收藏:0      [点我收藏+]

 

 

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

原文:https://www.cnblogs.com/adong7639/p/9597140.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!