亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 for 循環向字典添加鍵和值

如何使用 for 循環向字典添加鍵和值

阿晨1998 2023-10-18 16:32:21
所以我收到錯誤: RuntimeError:字典在迭代期間更改了大小。我有 2 個矩陣,一個用于 Xbox 信息,一個用于 PS4 信息 第一個函數根據 Xbox 矩陣創建字典。它查看矩陣內的每個列表,并從每個列表中獲取信息并將其添加到字典中。第二個函數獲取已經制作的字典 def create_dictionary_xbox并添加到其中。我正在嘗試使其打印出如下內容:{genre:{game:[info], game:[info]}}這是我的代碼:def create_dictionary_xbox(lists_of_data):    dictionary = {}    for list_ in lists_of_data:        game = list_[0]        genre = list_[2]        if genre not in dictionary:            dictionary[genre] = {game : list_[3:]}        elif genre in dictionary:            (dictionary[genre])[game] = list_[3:]                return dictionary        def create_dictionary_PS4(lists_of_data,dictionary):    for list_ in lists_of_data:        game = list_[0]        genre = list_[2]        for key in dictionary:            if genre not in dictionary:                dictionary[genre] = {game : list_[3:]}            elif genre in dictionary:                (dictionary[genre])[game] = list_[3:]    return dictionary
查看完整描述

1 回答

?
子衿沉夜

TA貢獻1828條經驗 獲得超3個贊

我假設數據結構是這樣的:


['gameX', 'useless_info', 'genreX', 'info', 'info', ...]

我想如果兩個列表上的數據結構相同,那么將兩個列表相加并僅交互一次會更容易,對吧?


complete_list = list_of_data1 + list_of_data2

    # make one list with all the data

dict_games = {genre : {} for genre in set([x[2] for x in complete_list])}

    # make a dict of dict with all genres


for game, _, genre, *info in complete_list:

    if game in dict_games[genre]:

        # check if the game exits on both list of data and sum the info

        info = info + dict_games[genre][game]

    dict_games[genre].update({game: info})

如果您想對兩個列表中出現的同一游戲的信息進行求和,我認為這是最簡單的方法。但如果你想丟棄信息,那么你可以按優先級對數據列表求和,或者如果你想創建一些規則來丟棄信息,那么我建議在數據結構上附加一個標志,并在稍后更新 dict_games 時使用它。請告訴我它是否有效或者是否有什么不太清楚。


查看完整回答
反對 回復 2023-10-18
  • 1 回答
  • 0 關注
  • 143 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號