我怎樣才能從這樣的串列中只提取一天?
date_data = [None, None, None, None, '2014-01-05', '2014-01-06', '2014-01-07', None, None, '2014-01-10']
我嘗試了一些不同的 lambda 函式,例如:
Date_List = [d for y, m, d in map(lambda x: str(x).split('-'), date_data) if y != None if m != None if d != None]
或者
test = [datetime.strptime(i, '%Y-%m-%d') for i in date_data]
test1 = [datetime.strftime(i, '%d') for i in test]
但我無法得到正確的輸出,即:
date_data = [None, None, None, None, '05', '06', '07', None, None, '10']
有人知道如何做到這一點嗎?
uj5u.com熱心網友回復:
盡管您可以這樣做,但根據您的初始運行:
Date_List = [x.split('-')[2] if x else None for x in date_data]
它遍歷串列元素并附加一個無,如果該元素是一個無開頭的元素,如果它是一個元素,那么你可以得到這一天
uj5u.com熱心網友回復:
一旦你習慣strptime了獲取一個datetime物件,你就可以呼叫該day屬性來檢索你正在尋找的值。我鼓勵基于連字符位置的過度字串決議,因為它對易失性輸入資料更健壯。
from datetime import datetime
dates = [None, None, None, None, '2014-01-05', '2014-01-06', '2014-01-07', None, None, '2014-01-10']
result = []
for date in dates:
if date is None:
result.append(None)
else:
result.append(datetime.strptime(date, '%Y-%m-%d').day)
print(result) # [None, None, None, None, 5, 6, 7, None, None, 10]
uj5u.com熱心網友回復:
這是完成作業的快速串列理解
new_list = [i.split("-")[-1] if "-" in str(i) else i for i in list]
[None, None, None, None, '05', '06', '07', None, None, '10']
只需遍歷您的原始串列,如果有 - 在拆分元素的字串版本中 - 并寫入最后一個元素。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520242.html
