2 回答

TA貢獻1893條經(jīng)驗 獲得超10個贊
使用字符串切片和datetime.strptime:
from datetime import datetime
transactions = ['transaction_report_for_01_02_2013.json', 'transaction_report_for_01_03_2017.json',
'transaction_report_for_08_03_2015.json',
'transaction_report_for_09_03_2015.json']
def custom_sort(filename):
# assuming a constant string end length slice the date and parse it
return datetime.strptime(filename[-15:-5], '%d_%m_%Y')
print(transactions)
#['transaction_report_for_01_02_2013.json', 'transaction_report_for_01_03_2017.json', 'transaction_report_for_08_03_2015.json', 'transaction_report_for_09_03_2015.json']
transactions.sort(key=custom_sort)
print(transactions)
#['transaction_report_for_01_02_2013.json', 'transaction_report_for_08_03_2015.json', 'transaction_report_for_09_03_2015.json', 'transaction_report_for_01_03_2017.json']

TA貢獻1812條經(jīng)驗 獲得超5個贊
用正則表達式?
import re
pattern = re.compile(r'^.*(\d{2})_(\d{2})_(\d{4}).*$')
keys = [x.match.group(3)+x.match.group(1)+x.match.group(2)
for x in filenames
]
filenames = [y for x,y in sorted(zip(keys,filenames))]
- 2 回答
- 0 關(guān)注
- 131 瀏覽
添加回答
舉報