📜  Python - 从列表中查找最近的日期

📅  最后修改于: 2022-05-13 01:54:35.382000             🧑  作者: Mango

Python - 从列表中查找最近的日期

给定一个日期和日期列表,任务是编写一个Python程序,以在给定的输入日期列表中找到与输入日期最近的日期。

例子:

方法 #1:使用min() +字典理解+ abs()

在这种情况下,使用 abs() 计算每个日期与给定日期的差异作为键和日期作为值。 min(),用于获取最小键差,其值为结果。

Python3
# Python3 code to demonstrate working of
# Nearest date in List
# Using min() + dictionary comprehension + abs()
from datetime import datetime
  
# initializing datelist
test_date_list = [datetime(2020, 4, 8), datetime(2016, 8, 18), 
                  datetime(2018, 9, 24), datetime(2019, 6, 10),
                  datetime(2021, 8, 10)]
               
# printing original list
print("The original list is : " + str(test_date_list))
  
# initializing test date 
test_date = datetime(2017, 6, 6)
  
# get all differences with date as values 
cloz_dict = { 
  abs(test_date.timestamp() - date.timestamp()) : date 
  for date in test_date_list}
  
# extracting minimum key using min()
res = cloz_dict[min(cloz_dict.keys())]
  
# printing result
print("Nearest date from list : " + str(res))


Python3
# Python3 code to demonstrate working of
# Nearest date in List
# Using min() + abs() + lambda
from datetime import datetime
  
# initializing datelist
test_date_list = [datetime(2020, 4, 8), datetime(2016, 8, 18), 
                  datetime(2018, 9, 24), datetime(2019, 6, 10),
                  datetime(2021, 8, 10)]
               
# printing original list
print("The original list is : " + str(test_date_list))
  
# initializing test date 
test_date = datetime(2017, 6, 6)
  
# shorthand using lambda function for compact solution
res = min(test_date_list, key=lambda sub: abs(sub - test_date))
  
# printing result
print("Nearest date from list : " + str(res))


输出:

方法#2:使用 min() + abs() + lambda

解决此问题的另一种更简单的方法是使用 min() 获取差异并捕获最小值。这是一种灵活的方法,不仅可以扩展到日期时间,还可以扩展到每种数据类型。

蟒蛇3

# Python3 code to demonstrate working of
# Nearest date in List
# Using min() + abs() + lambda
from datetime import datetime
  
# initializing datelist
test_date_list = [datetime(2020, 4, 8), datetime(2016, 8, 18), 
                  datetime(2018, 9, 24), datetime(2019, 6, 10),
                  datetime(2021, 8, 10)]
               
# printing original list
print("The original list is : " + str(test_date_list))
  
# initializing test date 
test_date = datetime(2017, 6, 6)
  
# shorthand using lambda function for compact solution
res = min(test_date_list, key=lambda sub: abs(sub - test_date))
  
# printing result
print("Nearest date from list : " + str(res))

输出: