I have datetime.date
objects stored in a list and would like to get the index of the last datetime.date before a comparison datetime.date
stored in a variable. In the example below, the last datetime.date
object surpassed by the comparison date would be datetime.date(2022, 2, 1)
with an index of 2.
I have working code but it seems quite convoluted. I use a function (taken from here) to get a list of the index numbers of all dates occuring before the comparison date, then getting the value of the last index in this list. A simpler approach would be most welcome.
import datetime
def get_index(list_of_elems, condition):
index_pos_list = []
for i in range(len(list_of_elems)):
if condition(list_of_elems[i]) == True:
index_pos_list.append(i)
return index_pos_list
dates = [datetime.date(2020, 2, 1),
datetime.date(2021, 2, 1),
datetime.date(2022, 2, 1),
datetime.date(2023, 2, 1),
datetime.date(2024, 2, 1),
datetime.date(2025, 2, 1)]
comparison_date = datetime.date(2022, 11, 5)
index_pos_list = get_index(dates, lambda x : x < comparison_date)
last_index = len(index_pos_list) - 1
print(last_index)
CodePudding user response:
Since you only need to get the last index of a date before the comparison date, I'd suggest creating a separate function get_last_index
which does exactly that.
Also, in this case it's better to iterate over the list in reverse order, so that we can just return the first encountered index where the condition matches as true.
def get_last_index(list_of_elems, condition) -> int:
for i in range(len(list_of_elems) -1, -1, -1):
if condition(list_of_elems[i]):
return i
# no date earlier than comparison date is found
return -1
last_index = get_last_index(dates, lambda x: x < comparison_date)
print(last_index)
Result:
2
Note that the function could also be rewritten to use a generator expression, with next
to get the first result of the expression:
def get_last_index(list_of_elems, condition, default_idx=-1) -> int:
try:
return next(i for i in range(len(list_of_elems) - 1, -1, -1)
if condition(list_of_elems[i]))
except StopIteration: # no date earlier than comparison date is found
return default_idx
CodePudding user response:
You could combine two of the lines and then you need to sort the list so that your output is correct:
import datetime
def get_index(list_of_elems, condition):
index_pos_list = []
list = list_of_elems.sort() ####### sort
for i in range(len(list_of_elems)):
if condition(list_of_elems[i]) == True:
print(list_of_elems[i])
index_pos_list.append(i)
return index_pos_list
dates = [datetime.date(2020, 2, 1),
datetime.date(2021, 2, 1),
datetime.date(2022, 2, 1),
datetime.date(2023, 2, 1),
datetime.date(2024, 2, 1),
datetime.date(2025, 2, 1)]
comparison_date = datetime.date(2022, 11, 5)
index_pos_list = len(get_index(dates, lambda x : x < comparison_date)) - 1 ##### combined lines
print(index_pos_list)