为什么我的Python for loop remove()会更改在循环之前声明的变量?

2024-05-28 23:43:48 发布

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

下面是我的函数的简化版本,它比较三组数字,并找到相关性最高的两组:

inputs = ['vars_one', 'vars_two', 'vars_three']
def MostCorrelatedInputs(inputs):
    correlation = 0
    saved_inputs = inputs
    for i in inputs:
        testlist = saved_inputs
        testlist.remove(i)
        new_correlation = FindCorrelation(testlist)
        if new_correlation > correlation:
            correlation = new_correlation
            outputs = testlist
    return outputs

问题是,当我运行函数时,remove()函数似乎改变了保存的\u inputs变量,即使我在inputs上调用它。这是垃圾回收的问题吗?为什么保存的_inputs变量会被for循环更改,如果remove()希望更改此变量,是否有更好的方法来实现我的目标?你知道吗


Tags: 函数版本newfor数字varsoutputsone
3条回答

所以当你做一个:

saved_inputs = inputs

以及

testlist = saved_inputs

testlist和保存的输入都引用相同的object/list-inputs。你知道吗

你需要一份清单的“深度副本”。i-e公司

引用您的示例代码:

testlist = saved_inputs

testlist.remove('vars_one')

print testlist
print saved_inputs

这将导致:

['vars_two', 'vars_three']
['vars_two', 'vars_three']

你必须这样做:

testlist = list(saved_inputs)

testlist.remove('vars_one')

print testlist
print saved_inputs

要获得结果:

['vars_two', 'vars_three']
['vars_one', 'vars_two', 'vars_three']

我想这正是你所期待的。你知道吗

您正在声明testlist以引用与输入相同的引用。你知道吗

因此,如果要使testlist只包含值而不包含引用,则需要对列表执行以下操作:

inputlist = inputs[:]

我给你一个提示:

>>>a = [1,2,3]
>>>b = a
>>>b.remove(1)
>>>a
[2, 3]

这是因为b引用的对象与a引用的对象相同!如果您从b中删除某些内容,那么您也将从a引用的对象中删除它。要更改此设置(如创建副本),请执行以下操作

>>>b = a[:]
>>>b.remove(1)
>>>a
[1, 2, 3]
>>>b
[2, 3]

相关问题 更多 >

    热门问题