【问题标题】:Print Not Matching With An Array I'm Appending To打印与我要附加到的数组不匹配
【发布时间】:2020-05-31 09:24:15
【问题描述】:

我正在尝试创建一个函数,该函数接受一个数字数组,并在两个数组中为您提供这些数字可以包含的每个组合。

我的问题是我可以打印我想要的确切结果,但是当我尝试将结果保存到变量中时,出于某种原因,我的数组中出现了相同的子数组。

代码如下:

test = []
def partitioner(array1, array2):
    a = array1
    b = array2
    for _ in range(len(b)):
        a.append(b[0])
        del b[0]

        if(len(b) >= 1 and len(a) >= 1):
            print([a, b])       # This part right here, I'm printing the expected
            test.append([a, b]) # But this array is getting the actual
        partitioner(a, b)
        b.append(a[-1])
        del a[-1]

partitioner([], [x for x in range(3)])
print(test)

预期:

[
[[0], [1, 2]],
[[0, 1], [2]],
[[0, 2], [1]],
[[1], [2, 0]],
[[1, 2], [0]],
[[1, 0], [2]],
[[2], [0, 1]],
[[2, 0], [1]],
[[2, 1], [0]]]

实际:

[
[[], [0, 1, 2]],
[[], [0, 1, 2]],
[[], [0, 1, 2]], 
[[], [0, 1, 2]], 
[[], [0, 1, 2]], 
[[], [0, 1, 2]], 
[[], [0, 1, 2]], 
[[], [0, 1, 2]], 
[[], [0, 1, 2]]]

【问题讨论】:

    标签: python list partition-problem


    【解决方案1】:

    ab 是列表,因此当递归的每次迭代都用最后一个值覆盖它们时,它也会更改 test 中的值。改为附加 ab 的副本

    test.append([a[:], b[:]])
    

    【讨论】:

      猜你喜欢
      • 2020-10-03
      • 2014-12-10
      • 2021-12-13
      • 2012-12-13
      • 1970-01-01
      • 1970-01-01
      • 2013-07-04
      • 2020-03-24
      • 1970-01-01
      相关资源
      最近更新 更多