python-3.x 填写日期的缺失值

1l5u6lss  于 2023-01-06  发布在  Python
关注(0)|答案(1)|浏览(129)

我可以拉平均货币兑换(EUR-〉PLN)在这里:https://api.nbp.pl/api/exchangerates/rates/a/eur/2022-12-01/2022-12-31/?format=json
在“rates”字段中,我有值:

"rates":[{"no":"232/A/NBP/2022","effectiveDate":"2022-12-01","mid":4.6892},{"no":"233/A/NBP/2022","effectiveDate":"2022-12-02","mid":4.6850},{"no":"234/A/NBP/2022","effectiveDate":"2022-12-05","mid":4.6898},{"no":"235/A/NBP/2022","effectiveDate":"2022-12-06","mid":4.6995},{"no":"236/A/NBP/2022","effectiveDate":"2022-12-07","mid":4.6968},{"no":"237/A/NBP/2022","effectiveDate":"2022-12-08","mid":4.6976},{"no":"238/A/NBP/2022","effectiveDate":"2022-12-09","mid":4.6821},{"no":"239/A/NBP/2022","effectiveDate":"2022-12-12","mid":4.6912},{"no":"240/A/NBP/2022","effectiveDate":"2022-12-13","mid":4.6945},{"no":"241/A/NBP/2022","effectiveDate":"2022-12-14","mid":4.6886},{"no":"242/A/NBP/2022","effectiveDate":"2022-12-15","mid":4.6843},{"no":"243/A/NBP/2022","effectiveDate":"2022-12-16","mid":4.6934},{"no":"244/A/NBP/2022","effectiveDate":"2022-12-19","mid":4.6886},{"no":"245/A/NBP/2022","effectiveDate":"2022-12-20","mid":4.6804},{"no":"246/A/NBP/2022","effectiveDate":"2022-12-21","mid":4.6648},{"no":"247/A/NBP/2022","effectiveDate":"2022-12-22","mid":4.6551},{"no":"248/A/NBP/2022","effectiveDate":"2022-12-23","mid":4.6364},{"no":"249/A/NBP/2022","effectiveDate":"2022-12-27","mid":4.6558},{"no":"250/A/NBP/2022","effectiveDate":"2022-12-28","mid":4.6938},{"no":"251/A/NBP/2022","effectiveDate":"2022-12-29","mid":4.6969},{"no":"252/A/NBP/2022","effectiveDate":"2022-12-30","mid":4.6899}]

但我没有一个月中所有日期的值-例如2022-12-03、2022-12-04等。我希望实现的是分配最后一个已知值(“mid”),因此,例如对于2022-12-03,它应该是2022-12-02的“mid”值,对于2022 -12-04,它也应该是2022-12-02的值
这是一段代码,我必须转换abouve响应字典:日期-〉中:

exchange_rates = {}
response = requests.get("https://api.nbp.pl/api/exchangerates/rates/a/eur/2022-12-01/2022-12-31/?format=json")
rates = response.json()['rates']
for i in range(len(rates)):
    exchange_rates[rates[i]['effectiveDate']]=rates[i]['mid']

我不知道算法应该是什么样子的...任何提示都非常感谢。

disbfnqx

disbfnqx1#

我们可以使用for循环:

exchange_rates = {}
response = requests.get("https://api.nbp.pl/api/exchangerates/rates/a/eur/2022-12-01/2022-12-31/?format=json")
rates = response.json()['rates']
for i in range(len(rates)):
    exchange_rates[rates[i]['effectiveDate']]=rates[i]['mid']

# since 2022-12-01 has a rate, we can use it as the initial value
prev_rate = exchange_rates['2022-12-01']

# use a for loop to go from 2022-12-02 to 2022-12-31
for i in range(2, 32):
    date = '2022-12-' + str(i).zfill(2)
    if date in exchange_rates:
        prev_rate = exchange_rates[date]
    else:
        exchange_rates[date] = prev_rate

相关问题