首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何保存一本互换项目的字典?

如何保存一本互换项目的字典?
EN

Stack Overflow用户
提问于 2018-05-29 07:04:29
回答 1查看 49关注 0票数 2

函数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循环中的项值都会返回到原始值。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-29 07:15:23

您的错误是由于dict是可变的。你要做的是:

  1. 交换两个元素
  2. 使用交换的元素获取网格的快照
  3. 交换回元素。

虽然,如果您使用相同的dict而不是拷贝作为快照,但在交换回快照时,您也会交换快照中的项目。

相反,您应该做的是:

  1. 创建格网的副本
  2. 交换copy

中的元素

为此,请使用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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50574342

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档