繁体   English   中英

如何检查字典中是否存在某个日期,如果没有,则返回最近的可用日期?

[英]How to check if a certain date is present in a dictionary and if not, return the closest date available?

我有一本包含许多排序日期的字典。 我如何在 Python 中编写一个循环来检查某个日期是否在字典中,如果没有,它返回最接近的可用日期? 我希望它可以工作,如果在日期减去一天后,它会再次检查它现在是否存在于字典中,如果不存在,它会再次减去直到找到现有日期。

提前致谢

from datetime import timedelta

def function(date):
    if date not in dictio:
        date -= timedelta(days=1)
    return date

您正在寻找的可能是一个 while 循环,但要小心,因为如果它找不到日期,它将运行到无限。 也许您想定义一个尝试限制,直到脚本放弃?

from datetime import timedelta, date

d1 = {
    date(2019, 4, 1): None
}

def function(date, dictio):
    while date not in dictio:
        date -= timedelta(days=1)

    return date


res_date = function(date.today(), d1)
print(res_date)

我做了一个递归函数来解决你的问题:

import datetime
def find_date(date, date_dict):
    if date not in date_dict.keys():
        return find_date(date-datetime.timedelta(days=1), date_dict)
    else:
        return date

我不知道你的字典的内容是什么,但下面的例子应该向你展示它是如何工作的:

import numpy as np

# creates a casual dates dictionary
months = np.random.randint(3,5,20)
days = np.random.randint(1,30,20)
dates = {
    datetime.date(2019,m,d): '{}_{:02}_{:02}'.format(2019,m,d) 
    for m,d in zip(months,days)}

# select the date to find
target_date = datetime.date(2019, np.random.randint(3,5), np.random.randint(1,30))

# print the result
print("The date I wanted: {}".format(target_date))
print("The date I got: {}".format(find_date(target_date, dates)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM