zoukankan      html  css  js  c++  java
  • 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(...))
  • 相关阅读:
    Java面试知识点总结
    Log4j常用配置及使用
    Eclipse+tomcat+axis2进行web service部署
    iframe内点击a标签禁止滚动到顶部
    VScode首选项
    Bookmarks
    VScode常用插件
    slideout
    bs-loading
    iPhone X 上删除白条
  • 原文地址:https://www.cnblogs.com/adong7639/p/9597140.html
Copyright © 2011-2022 走看看