python – 如何根据我提供的特定订单进行排序
发布时间:2020-12-20 12:12:33 所属栏目:Python 来源:网络整理
导读:我试图在给定扩展名的目录中对文件进行排序,但提供了我先给出的订单.假设我想要扩展订单 ext_list = [ .bb,.cc,.dd,aa ] 我能想到的唯一方法就是浏览每一个文件 ??并在每次遇到特定扩展时将它们放在列表中. for subdir,dirs,files in os.walk(directory): if
我试图在给定扩展名的目录中对文件进行排序,但提供了我先给出的订单.假设我想要扩展订单
ext_list = [ .bb,.cc,.dd,aa ] 我能想到的唯一方法就是浏览每一个文件 for subdir,dirs,files in os.walk(directory): if file.endswith( '.bb') --> append file then go to the end of the directory then loop again if file.endswith( '.cc') -->append file and so on... return sorted_extension_list 然后最后 for file in sorted_extension_list : print file 解决方法
您可以将sorted()与自定义键一起使用:
import os my_custom_keymap = {".aa":2,".bb":3,".cc":0,".dd":1} def mycompare(f): return my_custom_keymap[os.path.splitext(f)[1]] files = ["alfred.bb","butters.dd","charlie.cc","derkins.aa"] print(sorted(files,key=mycompare)) 以上使用mycompare函数作为自定义键比较.在这种情况下,它会提取扩展名,并在my_custom_keymap字典中查找扩展名. 一种非常类似的方式(但更接近您的示例)可以使用列表作为地图: import os my_custom_keymap = [".cc",".dd",".aa",".bb"] def mycompare(f): return my_custom_keymap.index(os.path.splitext(f)[1]) files = ["alfred.bb",key=mycompare)) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |