第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Python 中對 MM/DD/YYYY 字符串數(shù)組進行排序的最有效方法?

在 Python 中對 MM/DD/YYYY 字符串數(shù)組進行排序的最有效方法?

Go
守候你守候我 2022-10-18 19:57:11
我正在嘗試使用來自https://senatestockwatcher.com/的數(shù)據(jù),特別是獲取最新文件。根據(jù) API 頁面,這需要獲取 Amazon S3 存儲桶中的文件列表,然后找到最新的并獲取它。我目前使用的代碼是:data = requests.get(url).textdata = xmltodict.parse(data)data = json.loads(json.dumps(data))data = data["ListBucketResult"]["Contents"]filenames = [item["Key"] for item in data if "data/" in item["Key"]][1:]filenames.sort()print(filenames)但是,我遇到的問題是文件名的格式為:transaction_report_for_01_02_2013.jsontransaction_report_for_01_03_2017.json對數(shù)組使用常規(guī) python.sort()函數(shù)不起作用,因為它從左到右讀取名稱字符串,因此忽略了年份。將這些文件從最新到最舊準確排序的最有效方法是什么?
查看完整描述

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']



查看完整回答
反對 回復(fù) 2022-10-18
?
ABOUTYOU

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))]


查看完整回答
反對 回復(fù) 2022-10-18
  • 2 回答
  • 0 關(guān)注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號