gpt4 book ai didi

python - 循环字典的内部列表,添加缺失的月份

转载 作者:行者123 更新时间:2023-12-01 02:26:00 25 4
gpt4 key购买 nike

我一直在努力解决如何循环遍历列表,将缺少的月份添加到原始字典中的 0。我正在考虑从 calendar 创建一个月份列表,循环遍历每个月,然后循环遍历我的数据中的每个月......但不太清楚如何更新字典缺少一个按正确顺序排列的月份。

import calendar

my_dict = {'Green Car':
[('January', 340),
('February', 2589),
('March', 12750),
('April', 114470),
('July', 4935),
('August', 1632),
('September', 61),
('December', 3409)],
'Red Truck':
[('January', 2325185),
('February', 209794),
('March', 201874),
('April', 19291),
('May', 18705),
('July', 22697),
('August', 22796)],
'Police Car':
[('January', 2037),
('February', 2620),
('March', 1480),
('April', 15630),
('July', 40693),
('August', 2329)],
'Zamboni':
[('January', 256),
('February', 426690),
('March', 589),
('April', 4740),
('May', 880),
('July', 1016),
('August', 106),
('September', 539),
('October', 598),
('November', 539),
('December', 470)],
'Witch Broom':
[('February', 350),
('March', 3520),
('October', 2703),
('November', 2221),
('December', 664)]
}


def fill_months(reported_months):
const_months = list(calendar.month_name)
x = 0
print("Looking for months in", reported_months)
# print(const_months)
for const_month in const_months:
for month in reported_months:
if const_month != month[0] and len(const_month) > 0:
print(const_month, month[0])
print("You don't have", const_month, "in the months group:", reported_months)


def main():
for commod, months in my_dict.items():
# print(commod)
# print(commod, months)
fill_months(months)


if __name__ == '__main__':
main()

对于每个键(“绿色汽车”、“红色卡车”等),我想循环遍历并添加值为 0 的缺失飞蛾。所以“绿色汽车”最终会是:

my_dict = {'Green Car': 
[('January', 340),
('February', 2589),
('March', 12750),
('April', 114470),
('May', 0),
('June', 0),
('July', 4935),
('August', 1632),
('September', 61),
('October', 0),
('November', 0),
('December', 3409)],
<小时/>

我对此有所了解 - 但逻辑感觉有点困惑:

def fill_months(reported_months):
const_months = list(calendar.month_name)
x = 0
temp_months = []
for i in reported_months:
temp_months.append(i[0])
print("Looking for months in", reported_months)
# print(const_months)
for const_month in const_months:
if len(const_month) > 0:
if const_month not in temp_months:
reported_months.insert(x-1, (const_month, 0))
x += 1
print(reported_months)

最佳答案

添加缺失月份的逻辑必须检查的就是月份是否与您拥有的某些月份名称列表(months)的索引不匹配。如果匹配则递增,并循环直到覆盖了 months 的每个成员。

months = ['January', 'February', 'March', 'April', 'May', 'June', 
'July', 'August', 'September', 'October', 'November', 'December']

def add_missing_months(vehicle_d):
for vehicle in vehicle_d:
ind = 0
month_l = vehicle_d[vehicle]
while ind < len(months):
if ind >= len(month_l) or month_l[ind][0] != months[ind]:
month_l.insert(ind, (months[ind], 0))
else:
ind += 1
return vehicle_d

关于python - 循环字典的内部列表,添加缺失的月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47399102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com