当我将一个数组复制到另一个数组时,为什么两个数组都被修改了?
Why are both of the arrays being modified when I copy one array into another?
我正在尝试解决 8puzzle 问题,为此,我需要当前状态的相邻元素。
当前状态(或数据)如下所示 - 一个二维数组,其中 0 表示空白状态。
1 0 2
3 4 5
6 7 8
我创建了一个带有 5 个参数的函数 -
零的 x 和 y 位置 (a,b)
要交换的元素索引的 x 和 y 位置(c,d)
data,即棋盘当前状态的数组
此函数将空白位置与数组中的适当元素交换,然后将当前板保存在列表中result_state。
然后它再次将这两个值交换回它们的原始位置,以便以后可以计算更多新状态。这就是它的样子 -
def append_in_list(self,a,b,c,d,data=None):
#print(data)
#print(store_values)
result_state = []
tmp = data[a][b]
data[a][b] = data[c][d]
data[c][d] = tmp
for i in range(0,len(data)):
result_state.append(data[i])
print(result_state)
tmp = data[c][d]
data[c][d] = data[a][b]
data[a][b] = tmp
#print(data)
print(result_state)
return result_state
这个输出是当 运行 一次是-
[[1, 4, 2], [3, 0, 5], [6, 7, 8]]
[[1, 0, 2], [3, 4, 5], [6, 7, 8]]
为什么result_state里面没有修改却发生了变化?
预期输出 -
[[1, 4, 2], [3, 0, 5], [6, 7, 8]]
[[1, 4, 2], [3, 0, 5], [6, 7, 8]]
有人可以指出我犯的错误吗?
此外,我需要将此函数的输出保存在一个包含多个元素的列表中,每个元素都是此函数的输出。我该怎么做?
预先感谢您的帮助。
使用:
# Creates a new list (copy of data[i]).
# This operation is O(len(data[i])).
result_state.append(data[i][:])
而不是:
# Does not create a new list (does not copy data[i]).
# Both result_state[i] and data[i] points to the same list.
# Hence, any modification will be visible in both of them.
# This operation is O(1).
result_state.append(data[i])
Also, I need to save the output of this function in a list which will contain multiple elements, each element being an output of this function. How should I do that?
outputs = []
outputs.append(append_in_list(0, 1, 1, 1, data))
我正在尝试解决 8puzzle 问题,为此,我需要当前状态的相邻元素。
当前状态(或数据)如下所示 - 一个二维数组,其中 0 表示空白状态。
1 0 2
3 4 5
6 7 8
我创建了一个带有 5 个参数的函数 - 零的 x 和 y 位置 (a,b)
要交换的元素索引的 x 和 y 位置(c,d)
data,即棋盘当前状态的数组
此函数将空白位置与数组中的适当元素交换,然后将当前板保存在列表中result_state。 然后它再次将这两个值交换回它们的原始位置,以便以后可以计算更多新状态。这就是它的样子 -
def append_in_list(self,a,b,c,d,data=None):
#print(data)
#print(store_values)
result_state = []
tmp = data[a][b]
data[a][b] = data[c][d]
data[c][d] = tmp
for i in range(0,len(data)):
result_state.append(data[i])
print(result_state)
tmp = data[c][d]
data[c][d] = data[a][b]
data[a][b] = tmp
#print(data)
print(result_state)
return result_state
这个输出是当 运行 一次是-
[[1, 4, 2], [3, 0, 5], [6, 7, 8]]
[[1, 0, 2], [3, 4, 5], [6, 7, 8]]
为什么result_state里面没有修改却发生了变化?
预期输出 -
[[1, 4, 2], [3, 0, 5], [6, 7, 8]]
[[1, 4, 2], [3, 0, 5], [6, 7, 8]]
有人可以指出我犯的错误吗?
此外,我需要将此函数的输出保存在一个包含多个元素的列表中,每个元素都是此函数的输出。我该怎么做?
预先感谢您的帮助。
使用:
# Creates a new list (copy of data[i]).
# This operation is O(len(data[i])).
result_state.append(data[i][:])
而不是:
# Does not create a new list (does not copy data[i]).
# Both result_state[i] and data[i] points to the same list.
# Hence, any modification will be visible in both of them.
# This operation is O(1).
result_state.append(data[i])
Also, I need to save the output of this function in a list which will contain multiple elements, each element being an output of this function. How should I do that?
outputs = []
outputs.append(append_in_list(0, 1, 1, 1, data))