我有那些清單
dates = ['2022-10-16 17:00:00', '2022-10-16 18:00:00', '2022-10-16 21:00:00', '2022-10-16 22:00:00']
values = [1920.0, 570.0, 1680.0, 900.0]
我正在嘗試根據早/晚創建一個字典,所以我撰寫了以下代碼
def to_dict(self):
my_dict = {}
for i in range(len(dates)):
hour = dt.datetime.strptime(date[i], "%Y-%m-%d %H:%M:%S").hour
if 6 < hour <= 17:
my_dict[date[i][:11] "06:00:00"] = [value[i]]
else:
my_dict[date[i][:11] "00:00:00"] = [value[i]]
print(my_dict)
return my_dict
我想得到這些結果
{'2022-10-16 06:00:00': [1920.0], '2022-10-16 00:00:00': [570.0, 1680.0, 900.0]}
但不知何故,我得到了這些
{'2022-10-16 06:00:00': [1920.0], '2022-10-16 00:00:00': [900.0]}
為什么串列中只有一個值?
uj5u.com熱心網友回復:
您需要append一個 dict 條目,而不是簡單地分配給它:
def to_dict(self):
my_dict = {}
for date, value in zip(dates, values):
d = dt.datetime.strptime(date, "%Y-%m-%d %H:%M:%S")
h = 6 if 6 < d.hour <= 17 else 0
d = d.replace(hour=h)
my_dict.setdefault(str(d), []).append(value)
return my_dict
uj5u.com熱心網友回復:
import datetime
dates = ['2022-10-16 17:00:00', '2022-10-16 18:00:00', '2022-10-16 21:00:00', '2022-10-16 22:00:00']
values = [1920.0, 570.0, 1680.0, 900.0]
my_dict = {}
for datetimeStr, value in zip(dates, values):
datetime_ = datetime.datetime.strptime(datetimeStr, "%Y-%m-%d %H:%M:%S")
if 6 < datetime_.hour and datetime_.hour <= 17:
key = datetime_.replace(hour=6).isoformat(sep=" ")
else:
key = datetime_.replace(hour=0).isoformat(sep=" ")
my_dict.setdefault(key, []).append(value)
print(my_dict)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/515882.html
標籤:Python列表字典
上一篇:創建一個包含串列的df新列
