简体   繁体   中英

Creating list of lists containing objects in python

I am trying to put a custom object into a 2d list and I'm getting very confused. Here's what I have:

Here's the cell class:

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

and my insertion object (where I take a grid/ maze and put the data into objects):

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

This does work, but what I really want is cellGrid to be a 2d list, just like grid, except that it will contain cell objects intstead of a string. I would like to be able to acceess it as cellGrid[0][0].what for example. How should I accomplish this?

If you want to do that you need to create a 'row' in the first loop to add into the main grid array. You then append cells to this row, and append the whole row to the grid.

Like so:

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

Use list comprehensions to create a list of lists full of None s. Change cellGrid initialization to:

cellGrid = [ [None for i in range(c)] for j in range(r)]

then you do

cellGrid[x][y] = Cell(what,cost)

Full code example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM