python对目录下的文件进行 多条件排序
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python对目录下的文件进行 多条件排序,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2554字,纯文字阅读大概需要4分钟。
内容图文
在进入正题之前,先介绍一下基础知识:
1、sort(),方法:就是对列表内容进行正向排序,直接在原列表进行修改,返回的是修改后的列表
lists =[1, 5, 10, 8, 6]
lists.sort()
print(lists)
>>> [1, 5, 6, 8, 10]
2、sorted() 方法: 对列表进行排序后,返回一个新的列表,而原列表不变。并且sorted()方法可以用在任何数据类型的序列中,而返回的总是一个列表的形式。
lists = [1, 5, 10, 8, 6] a = sorted(lists) print(lists) >>>[1, 5, 10, 8, 6] print(a) >>>[1, 5, 6, 8, 10]
3、进行多条件排序,使用参数 key 即可,其返回的顺序就是按照元组的顺序 。如果想要第一个顺序,第二个逆序,只需要在 x[1] 前面加上 -x[1]
lists = [(2, 5), (2, 3), (1, 2), (4, 2), (3, 4)] lists.sort(key=lambda x: (x[0], x[1])) print(lists) >>>[(1, 2), (2, 3), (2, 5), (3, 4), (4, 2)]
好,介绍完之后,下面进入正题,自定义顺序 读取文件 多条件排序。
如图,要让下面这些文件进行自己想要的顺序排序,首先根据月份排,然后依据日期排;即先五月,从 5_1 到 5_15,然后再到 6_1 ,如果只是单纯的采用 sort() 和sorted()肯定是不能实现的,需要自定义方式,进行排序。
那么怎么来排序呢?
思路就是: 先对文件进行分割,得到 月份 和 天数,然后利用sort() 的key值,进行排序。
import os path = ‘..\\url\\‘ file_selected = os.listdir(path) month = [‘Jan‘, ‘Feb‘, ‘Mar‘, ‘Apr‘, ‘May‘, ‘Jun‘, ‘Jul‘, ‘Aug‘, ‘Sep‘, ‘Oct‘, ‘Nov‘, ‘Dec‘] file_tem = [] file_comp = [] for file in file_selected: file_tem.append(file) # [file] value = file.split("_")[1].split("")[0] ind = month.index(value) # 得到月份的下标 file_tem.append(ind) # [file,ind] num = int(file.split("_")[1].split("")[1]) # 得到天数 file_tem.append(num) # [file,ind,num] file_comp.append(file_tem) # 得到[[file,ind,num],[file2,ind2,num2]]的形式 file_tem = [] file_comp.sort(key=lambda x: (x[1], x[2])) # 根据ind排,再根据num2 排 sorted_file = [x[0] for x in file_comp] print(sorted_file)
最终得到结果:
[‘Comprehensive Risk Report_May 1_ 2019 9-00-36 AM 076.html‘, ‘Comprehensive Risk Report_May 2_ 2019 9-00-36 AM 076.html‘, ‘Comprehensive Risk Report_May 3_ 2019 9-00-40 AM 593.html‘, ‘Comprehensive Risk Report_May 4_ 2019 9-00-46 AM 963.html‘, ‘Comprehensive Risk Report_May 5_ 2019 9-00-50 AM 724.html‘, ‘Comprehensive Risk Report_May 6_ 2019 9-00-53 AM 563.html‘, ‘Comprehensive Risk Report_May 7_ 2019 9-00-54 AM 080.html‘, ‘Comprehensive Risk Report_May 8_ 2019 9-00-37 AM 000.html‘, ‘Comprehensive Risk Report_May 9_ 2019 9-00-37 AM 935.html‘, ‘Comprehensive Risk Report_May 10_ 2019 9-00-39 AM 314.html‘, ‘Comprehensive Risk Report_May 11_ 2019 9-00-40 AM 031.html‘, ‘Comprehensive Risk Report_May 12_ 2019 9-00-42 AM 145.html‘, ‘Comprehensive Risk Report_May 13_ 2019 9-00-43 AM 490.html‘, ‘Comprehensive Risk Report_May 14_ 2019 9-00-13 AM 544.html‘, ‘Comprehensive Risk Report_May 15_ 2019 9-00-23 AM 408.html‘, ‘Comprehensive Risk Report_Jun 1_ 2019 9-00-27 AM 541.html‘]
这里为什么采用 file_tem = [ ] 而不是采用 file_tem.clear(),将在下一篇介绍。
原文:https://www.cnblogs.com/BackingStar/p/10986693.html
内容总结
以上是互联网集市为您收集整理的python对目录下的文件进行 多条件排序全部内容,希望文章能够帮你解决python对目录下的文件进行 多条件排序所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。