listA.append(listB [:])和listA.append(listB)有什么区别?

时间:2019-01-25 05:38:39

标签: python list

尝试在leetcode中进行python 3回溯。对于下面的代码,ans.append(stack [:])有效,而ans.append(stack)无效。

谢谢。

邮政编码。

def combine(self, n, k):
    """
    :type n: int
    :type k: int
    :rtype: List[List[int]]
    """
    nums = list(range(1,n+1))
    ans = []
    stack = []

    def backtracking( current_pos = 0, current_in_tuple = 0, rest = n):
        if current_in_tuple == k:
            ans.append(stack)
            return
        if rest + current_in_tuple < k:
            return

        for i in range(current_pos, n-k+current_in_tuple+1):
            stack.append(nums[i])
            backtracking(i+1, current_in_tuple+1, rest-1)
            stack.pop()


    backtracking()

    return ans

输入:4,2

Actual:[[],[],[],[],[],[]]
Expected:[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]

2 个答案:

答案 0 :(得分:0)

我会给您一些调试的提示,stack[:]创建一个新数组,而stack指的是您可以通过比较两者中的id来检查它的同一数组,请参见指向内存中的其他位置

In [1]: a=[1,2,3]

In [2]: id(a)
Out[2]: 139944147306568

In [3]: id(a[:])
Out[3]: 139944156641672

您可以在下面的示例中看到结果数组中实际发生的情况

In [4]: b=[]

In [5]: b.append(a)

In [6]: b
Out[6]: [[1, 2, 3]]

In [7]: a[0]=400

In [8]: b
Out[8]: [[400, 2, 3]]

请注意,修改ba被修改了,这就是代码输出错误的原因

我希望对您有所帮助:)

答案 1 :(得分:0)

区别在于listA.append(listB)将listB的浅拷贝添加到listA,这意味着,如果随后更改了listB(即,通过调用listB.pop()),该更改也将发生)在listA中。

但是listA.append(listB[:])制作了一个完全独立的副本,没有链接回到原始列表B。