如何在Python中不改变嵌套列表?

2024-04-24 05:57:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码:

 class World:
    def __init__(self, _map, pos):
        self.orig_map = _map
        self.map = self.orig_map[:]
        self.orig_pos = pos
        self.pos = list(self.orig_pos)
    def reset(self):
        self.map = self.orig_map[:]
        self.pos = list(self.orig_pos)
    def left(self):
        if self.pos[1]>0:
            self.pos[1]-=1
    def right(self):
        if not self.pos[1]+1>=len(self.map[0]):
            self.pos[1]+=1
    def up(self):
        if self.pos[0]>0:
            self.pos[0]-=1
    def down(self):
        if not self.pos[0]+1>=len(self.map):
            self.pos[0]+=1
    def eat(self):
        if self.map[self.pos[0]][self.pos[1]]==1:
            self.map[self.pos[0]][self.pos[1]]=0
            return True

应该发生什么:

^{pr2}$

发生了什么:

>>> w=World([[0,0,0],[0,1,0],[0,0,0]],(0,0))
>>> w.right()
>>> w.down()
>>> w.eat()
True
>>> w.reset()
>>> w.map
>>> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

可能出错的地方:self.map = self.orig_map[:]

上面的方法对于单个列表是有效的(经过多次尝试和测试),但是对于嵌套列表来说似乎不起作用。在


Tags: posselfrighttruemapworldlenif
2条回答

self.map = self.orig_map[:]你确实是在复制{}。但是,这是一个浅层副本,self.map中的元素仍然是self.orig_map中的元素相同的对象。在

相反,您需要做的是在您的__init__中制作self.map的一个self.map的副本。E、 g

import copy
...
    self.map = copy.deepcopy(self.orig_map)

您应该使用deepcopy

import copy

cop2 = copy.deepcopy(origin) 

它将递归地复制你的对象。在

相关问题 更多 >