打印与我要追加到的数组不匹配



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

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

这是代码:

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]]]

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

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

最新更新