我將datetime.date物件存盤在串列中,并希望在比較datetime.date存盤在變數中之前獲取最后一個 datetime.date 的索引。在下面的示例中,datetime.date比較日期超過的最后一個物件datetime.date(2022, 2, 1)的索引為 2。
我有作業代碼,但看起來很復雜。我使用一個函式(取自此處)來獲取比較日期之前發生的所有日期的索引號串列,然后獲取此串列中最后一個索引的值。更簡單的方法將是最受歡迎的。
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)
uj5u.com熱心網友回復:
由于您只需要在比較日期之前獲取日期的最后一個索引,我建議創建一個單獨的函式get_last_index來執行此操作。
此外,在這種情況下,最好以相反的順序遍歷串列,這樣我們就可以回傳第一個遇到的條件匹配為真的索引。
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)
結果:
2
請注意,該函式也可以重寫為使用生成器運算式,next以獲取運算式的第一個結果:
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
uj5u.com熱心網友回復:
您可以組合兩行,然后您需要對串列進行排序,以便您的輸出正確:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/363558.html
下一篇:蟒蛇條件匯總-修訂問題
