码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-09-06 12:32:50      阅读:608      评论:0      收藏:0      [点我收藏+]

标签:strong   spl   https   pre   split   key   遍历   png   div   

 

 

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

标签:strong   spl   https   pre   split   key   遍历   png   div   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!