首页 > 解决方案 > 列表发生了变异,但我没有直接对其进行变异

问题描述

在我的代码中,我尝试获取列表中元素的每个组合(我不想使用 itertools)。我通过用二进制计数来做到这一点,True然后False我将其应用于原始列表以获取所有组合(如果为真,则该数字将保留在非列表中,它将被删除)。现在我分配x了 0 所以[False, False, ...]在循环中,二进制数被添加。现在的问题是,如果我想将列表重置为 0,它不会改变,只是继续使用之前的列表。例如,在print(x)它打印的第一个代码中:[False,False,False,False,False,False,False,False,],[True,False,False,False,False,False,False,False,],[True,True,False,False,False,False,False,False,], ...]. 我可以打印xtest打印相同的结果,但我没有更改 x。有任何想法吗?

def get_combinations(arr):
    true = []
    x = []

    for thing in range(0,len(arr)):
        true.append(thing)
        x.append(False)

    true.sort(reverse=True)
    test = []
    final = []
    länge = 2**len(arr)
    for number in range(länge):

        test = x   <------------------------------- here
        #print(x) or print(test)
        for thing in true:

            if number / (2**thing) >= 1:
                test[thing] = True
                number -= 2**thing  
  
        final.append(test)

    return final


test = [1,2,4,5,3,1,5,13]
get_combinations(test)

如果我将行更改为:

test = [False,False,False,False,False,False,False,False]

它工作正常。

标签: python-3.xlistvariablesdplyr

解决方案


查找“Python 中的深拷贝与浅拷贝”

简而言之 :

x= [1,2,3] 

如果:

y = x       # x: [1,2,3]  , y: [1,2,3]
y[0] = 4    # x: [4,2,3]  , y: [4,2,3]

-- 请注意,y = x'y' 和 'x' 设置为相等,但更重要的是,'x' 和 'y' 是同一个对象……任何一个变化都会改变另一个。所以y[0] = 4也影响了谢x[0] is also now 4

另一方面 :

y = x.copy()  # x: [1,2,3]  , y: [1,2,3]
y[0] = 4      # x: [1,2,3]  , y: [4,2,3]

-- 这里 'y' 与 'x' 具有相同的值,但它们是不同的对象。通过更改 yy[0] = 4不会影响“x”。

在您的代码中:

test =x

和后面的'test'元素被修改,改变'x',然后在下一次迭代中,'x'for loop不再是[False,False...]

将该行替换为:

test =x.copy() 

推荐阅读