簡體   English   中英

在 while 循環中更新 python 字典的問題

[英]Issues with updating a python dictionary in a while loop

所以我是 python 的新手,並且在使用 while 循環更新字典時遇到了一些問題。 出於某種原因,代碼在更新調用之前遍歷索引 i,因此它只更新用作參數的列表中的最終項目。 例如,名稱的長度是 34,因此它只會添加每個列表中的第 34 項。 代碼如下所示:

def hurricane_data_entry(names, months, years, max_sustainted_winds, areas_affected, damages, deaths):
    hurricane_dictionary = {}
    i = 0
    while i < len(names):
        hurricane_dictionary.update({'Name': names[i], 'Month': months[i], 'Year': years[i], 'Max Sustained Wind': max_sustained_winds[i], 'Areas Affected': areas_affected[i], 'Damages': damages[i], 'Deaths': deaths[i]})
        i += 1
    return hurricane_dictionary

在我看來,您嘗試為每個名稱生成一系列字典。 您可以使用如下生成器:

def hurricane_data_entry(
        names: list,
        months: list,
        years: list,
        max_sustained_winds: list,
        areas_affected: list,
        damages: list,
        deaths: list,
        *,
        missing='N/A'
):
    """
    Generator yielding a dictionary for each name,
    where the other keys will be populated if the list it gets populated from
    is as long as the list of names
    """
    for name in names:
        yield {
            'Name': name,
            'Month': next(months, missing),
            'Year': next(years, missing),
            'Max Sustained Wind': next(max_sustained_winds, missing),
            'Areas Affected': next(areas_affected, missing),
            'Damages': next(damages, missing),
            'Deaths': next(deaths, missing),
        }

您只是在更新字典中的值,而不是添加鍵。 例如,您可以像這樣更新您的字典:

hurricane_dictionary.update({'Name'+str(i): names[i], 'Month'+str(i): months[i], 'Year'+str(i): years[i], 'Max Sustained Wind'+str(i): max_sustained_winds[i], 'Areas Affected'+str(i): areas_affected[i], 'Damages'+str(i): damages[i], 'Deaths'+str(i): deaths[i]})

我認為您想要的是字典列表或字典的字典。 您應該使用 for 循環和enumerate()

def hurricane_data_entry(names, months, years, max_sustainted_winds, areas_affected, damages, deaths):
    hurricane_dictionary = {}
    hurricane_list = []
    i = 0
    for i, name in enumerate(names):
        hurricane_dictionary[name] = {'Name': names[i], 'Month': months[i], 'Year': years[i], 'Max Sustained Wind': max_sustained_winds[i], 'Areas Affected': areas_affected[i], 'Damages': damages[i], 'Deaths': deaths[i]}
        hurricane_list.append({'Name': names[i], 'Month': months[i], 'Year': years[i], 'Max Sustained Wind': max_sustained_winds[i], 'Areas Affected': areas_affected[i], 'Damages': damages[i], 'Deaths': deaths[i]})
    return hurricane_dictionary, hurricane_list

dicts 的 dict 具有明顯的優勢,您可以使用hurricane_dictionary['Katrina']為每個颶風獲取一個 dict,而列表只是一個列表。 要獲得特定條目,您現在需要它的索引(例如hurricane_list[23] )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM