在创建2D数组/列表时遇到问题

时间:2015-08-18 11:54:46

标签: python arrays list shallow-copy

我在创建2D排列列表时遇到了困难。这是一个重现问题的最小代码

class Solution:
def permute(self, A):
    A = sorted(A)
    print A
    A_out = []
    A_out.append(A)
    for iter0 in range(4):
        A[0] = A[0] + 1
        print A
        A_out.append(A)
    return A_out

sol = Solution()
A = [1, 2, 3]
print sol.permute(A)

对于此特定输入(1,2,3),输出为

[1, 2, 3]
[2, 2, 3]
[3, 2, 3]
[4, 2, 3]
[5, 2, 3]
[[5, 2, 3], [5, 2, 3], [5, 2, 3], [5, 2, 3], [5, 2, 3]]

但所需的输出是

[1, 2, 3]
[2, 2, 3]
[3, 2, 3]
[4, 2, 3]
[5, 2, 3]
[[1, 2, 3], [2, 2, 3], [3, 2, 3], [4, 2, 3], [5, 2, 3]]

我认为它有深度复制/浅拷贝的东西,但我不知道如何纠正这个,因为我不熟悉Python。我该如何解决?

1 个答案:

答案 0 :(得分:5)

确实是浅层副本。您保持追加的列表A始终引用相同的值。这与Python中列表的可变性有关。

每次都需要附加列表的新副本,以使它们彼此独立。您可以使用切片运算符[:]来执行此操作,因为它会创建列表的新副本。所以你可以在调用append

时使用它
def permute(self, A):
    A = sorted(A)
    print A
    A_out = []
    A_out.append(A[:])
    while (self.checkVal(A) != -1) :
        A = self.nextState(A,self.checkVal(A))
        print A
        A_out.append(A[:])
    return A_out
相关问题