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

前端 未结 3 1947
醉酒成梦
醉酒成梦 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:50

    Use string join()

    for row in grid:
        print ''.join(*zip(*row))
    

    or as one-liner:

    print '\n'.join(''.join(*zip(*row)) for row in grid)
    

    but if would rather recommend you to change everything into:

    def grid_maker(h,w):
        grid = [["-" for _ in range(w)] for _ in range(h)]
        grid[0][0] = "o"
        return grid
    
    print '\n'.join(''.join(row) for row in grid_maker(5,5))
    

提交回复
热议问题