Python: how to print out a 2d list that is formatted into a grid?

前端 未结 3 1931
醉酒成梦
醉酒成梦 2021-01-14 10:11

Currently, I have made this code

def grid_maker(h,w):
    grid = [[[\"-\"] for i in range(w)] for i in range(h)]
    grid[0][0] = [\"o\"]
    print grid

>         


        
3条回答
  •  醉梦人生
    2021-01-14 10:55

    If you want to use the result of grid_maker(), you have to return its result, using return:

    def grid_maker(h, w):
        grid = [["-" for i in range(w)] for i in range(h)]
        grid[0][0] = "o"
        return grid
    

    I modified it, because I don't think that each element must be inside another list.

    To print the "grid", you could iterate through each row and then iterate through each element:

    def print_grid(grid):
        for row in grid:
            for e in row:
                print e,
            print
    

    Output:

    print_grid(grid_maker(3, 5))
    
    o - - - -
    - - - - -
    - - - - -
    

提交回复
热议问题