Python 打印与数组I'不匹配;我附加到
我正在尝试做一个函数,它接受一个数字数组,并给出这些数字的每一个组合,在两个数组中 我的问题是,我可以打印出我想要的确切结果,但当我试图将结果保存到变量中时,由于某种原因,我会在数组中收到相同的子数组垃圾邮件 代码如下:Python 打印与数组I'不匹配;我附加到,python,list,partition-problem,Python,List,Partition Problem,我正在尝试做一个函数,它接受一个数字数组,并给出这些数字的每一个组合,在两个数组中 我的问题是,我可以打印出我想要的确切结果,但当我试图将结果保存到变量中时,由于某种原因,我会在数组中收到相同的子数组垃圾邮件 代码如下: test = [] def partitioner(array1, array2): a = array1 b = array2 for _ in range(len(b)): a.append(b[0]) del b[0
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]]]
a
和b
是列表,因此,当使用最后一个值重写递归的每次迭代时,它也会更改test
中的值。改为附加一份a
和b
的副本
test.append([a[:], b[:]])