打印与我附加到的数组不匹配
Print Not Matching With An Array I'm Appending To
我正在尝试制作一个函数,它接受一个数字数组,并在两个数组中为您提供这些数字可以包含的所有组合。
我的问题是我可以打印出我想要的确切结果,但是当我尝试将结果保存到变量中时,出于某种原因,我的数组中出现了相同的子数组。
代码如下:
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[:]])
我正在尝试制作一个函数,它接受一个数字数组,并在两个数组中为您提供这些数字可以包含的所有组合。
我的问题是我可以打印出我想要的确切结果,但是当我尝试将结果保存到变量中时,出于某种原因,我的数组中出现了相同的子数组。
代码如下:
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[:]])