我试图将自定义对象放入2d列表中,我感到非常困惑。 这就是我所拥有的:
这是细胞类:
class Cell(object):
def __init__(self, what, cost):
self.what = what
self.parentx = -1
self.parenty = -1
self.f = 0
self.g = 0
self.h = 0
self.cost = cost
和我的插入对象(我带网格/迷宫并将数据放入对象中):
def insertion (r, c, grid):
cellGrid = []
for x in range(0, r):
for y in range(0, c):
if (grid[x][y] == '%'):
what = 0
cost = 100000000
elif(grid[x][y] == '-'):
what = 1
cost = 1
elif (grid[x][y] == '.'):
what = 2
cost = 0
else:
what = 3
cellGrid.append(Cell(what, cost))
return cellGrid
这确实有效,但我真正想要的是cellGrid是一个二维列表,就像网格,除了它将包含单元格而不是字符串。我希望能够将其作为cellGrid[0][0].what
加以承认。我应该怎样做到这一点?
答案 0 :(得分:2)
如果你想这样做,你需要创建一个'行'在第一个循环中添加到主grid
数组中。然后,将单元格附加到此行,并将整行附加到网格中。
像这样:
def insertion (r, c, grid):
cellGrid = []
for x in range(0, r):
row = []
for y in range(0, c):
if (grid[x][y] == '%'):
what = 0
cost = 100000000
elif(grid[x][y] == '-'):
what = 1
cost = 1
elif (grid[x][y] == '.'):
what = 2
cost = 0
else:
what = 3
row.append(Cell(what, cost))
cellGrid.append(row)
return cellGrid
答案 1 :(得分:1)
使用列表推导来创建一个包含None
个列表的列表。将cellGrid初始化更改为:
cellGrid = [ [None for i in range(c)] for j in range(r)]
然后你做
cellGrid[x][y] = Cell(what,cost)
完整代码示例:
def insertion (r, c, grid):
cellGrid = [ [None for i in range(c)] for j in range(r)]
for x in range(0, r):
for y in range(0, c):
if (grid[x][y] == '%'):
what = 0
cost = 100000000
elif(grid[x][y] == '-'):
what = 1
cost = 1
elif (grid[x][y] == '.'):
what = 2
cost = 0
else:
what = 3
cellGrid[x][y] = Cell(what,cost)
return cellGrid