函数swap_elements
必须交换dict
中的元素,并在交换回元素之前保留结果dict
的快照,以保持原始元素的完整性。
举个例子:
swap_elements({0: [1, 2], 1: [3, 4]}, [(0, 1), (1, 0)], (0, 0))
应该返回
{'entry 0': {0 :[2, 1], 1: [3, 4]},
'entry 1': {0: [3, 2], 1: [1, 4]}
下面是代码。
def swap_elements(grid, new_positions, current_x_y):
modified_grids_1 = {}
i = 0
# original = grid
for pos in new_positions:
# print(pos[0], pos[1], current_x_y[0], current_x_y[1])
# print(grid[pos[0]][pos[1]], grid[current_x_y[0]][current_x_y[1]])
grid[pos[0]][pos[1]], grid[current_x_y[0]][current_x_y[1]] = grid[current_x_y[0]][current_x_y[1]], grid[pos[0]][pos[1]]
# print_grid(grid)
modified_grids_1.update({"entry "+str(i): grid})
# print_grid(modified_grids[i])
i += 1
grid[current_x_y[0]][current_x_y[1]], grid[pos[0]][pos[1]] = grid[pos[0]][pos[1]], grid[current_x_y[0]][current_x_y[1]]
# print_grid(grid)
print(modified_grids_1)
# for k in modified_grids.keys():
# print_grid(modified_grids.get(k))
return modified_grids_1
我将更改后的网格值正确地插入到modified_grids_1
循环中的字典中。但是在for循环之外,所有插入到for循环中的项值都会返回到原始值。
发布于 2018-05-29 07:15:23
您的错误是由于dict
是可变的。你要做的是:
虽然,如果您使用相同的dict
而不是拷贝作为快照,但在交换回快照时,您也会交换快照中的项目。
相反,您应该做的是:
中的元素
为此,请使用copy.deepcopy
。
import copy
def swap_elements(grid, new_positions, current_x_y):
modified_grids_1 = {}
for i, pos in enumerate(new_positions):
# Make a copy of the grid beforehand
modified_grid = copy.deepcopy(grid)
modified_grid[pos[0]][pos[1]], modified_grid[current_x_y[0]][current_x_y[1]] = grid[current_x_y[0]][current_x_y[1]], grid[pos[0]][pos[1]]
modified_grids_1["entry "+str(i)] = copy.deepcopy(modified_grid)
print(modified_grids_1)
return modified_grids_1
swap_elements({0: [1, 2]}, [(0,0)], (0, 1)) # {'entry 0': {0: [2, 1]}}
注意,我还添加了一些改进,比如使用enumerate
而不是递增的变量来跟踪条目编号,使用item assignment而不是dict.update
。
https://stackoverflow.com/questions/50574342
复制相似问题