函数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循环中的项值都会返回到原始值。
https://stackoverflow.com/questions/50574342
复制相似问题