首页
学习
活动
专区
工具
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
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50574342

复制
相关文章

相似问题

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