python對目錄下的文件進行 多條件排序


在進入正題之前,先介紹一下基礎知識:

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(),將在下一篇介紹。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM