我有以下代碼:results = {'location': [], 'analysis_Elem 1': [], 'analysis_Elem 2': [], 'analysis_Elem 3': []}def collectResults(step): new_results = results for key in d: #here, d is another dictionary with a lot of results read from .csv file with the same keys as in the results dictionary for line in d[key]: if step in line[0]: new_results[key].append(float(line[-1].strip())/1000) for line in d[key]: if step in line[0]: new_results['location'].append(float(line[-4].strip())) return new_resultsres1 = collectResults('Time-step 7')res2 = collectResults('Time -step 2')在這個(gè)函數(shù)中,我試圖在一個(gè)字典中滿足 if 語句時(shí)收集結(jié)果,該字典由帶有相應(yīng)空列表的鍵組成。這個(gè)想法是每次調(diào)用函數(shù) collectResults() 時(shí),我都想獲得分配給變量的結(jié)果;比如上面的res1,res2。我遇到的問題是 new_results = results 行導(dǎo)致在第二次調(diào)用該函數(shù)后,字典 new_results(因此也是 res2)包括第二次調(diào)用擴(kuò)展的第一次調(diào)用的結(jié)果。我知道它們具有相同的內(nèi)存地址,這就是覆蓋的原因。對(duì)于列表,可以使用例如 list() 輕松解決。我無法在字典的情況下找到解決方案。需要怎么做才能獲得每次調(diào)用的解耦結(jié)果?
2 回答

紅顏莎娜
TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超13個(gè)贊
為什么不在字典上使用 copy() 方法而不是賦值(它只是將新名稱綁定到當(dāng)前字典)?
def collectResults(step):
new_results = results.copy()
添加回答
舉報(bào)
0/150
提交
取消