2 回答
TA贡献1893条经验 获得超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条经验 获得超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 关注
- 104 浏览
添加回答
举报