具有相同内存地址的解耦字典

2024-09-29 23:33:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

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_results

res1 = collectResults('Time-step 7')
res2 = collectResults('Time -step 2')

在这个函数中,当if语句在一个由键和相应的空列表组成的字典中得到满足时,我试图收集结果。其思想是每次调用collectResults()函数时,我都希望获得分配给变量的结果;比如上面的res1,res2。我遇到的问题是,line new\u results=results导致在第二次调用该函数之后,dictionary new\u results(因此也包括res2)包含第一次调用的结果,并用第二次调用扩展。我知道它们有相同的内存地址,这就是重写的原因。对于列表,可以使用例如list()轻松解决。我找不到解决词典问题的办法。要获得每个调用的解耦结果,需要做些什么


Tags: key函数innewfordictionaryifstep
2条回答

使用^{} module并将new_results = results替换为new_results = copy.deepcopy(results)

文档也很好地解释了为什么会发生这种行为

Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic shallow and deep copy operations (explained below).

为什么不在字典上使用copy()方法而不是赋值(赋值只是将新名称绑定到当前字典)

def collectResults(step):
    new_results = results.copy()

相关问题 更多 >

    热门问题