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

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

    If you want to "pretty" print your grid with each sublist on its own line, you can use pprint:

    >>> grid=[[['o'], ['-'], ['-'], ['-'], ['-']], [['-'], ['-'], ['-'], ['-'], ['-']], [['-'], ['-'], ['-'], ['-'], ['-']]]
    
    >>> from pprint import pprint
    >>> pprint(grid)
    
    [[['o'], ['-'], ['-'], ['-'], ['-']],
     [['-'], ['-'], ['-'], ['-'], ['-']],
     [['-'], ['-'], ['-'], ['-'], ['-']]]
    

    It will still show each element as a list, as you defined it, if you want to show them as strings you'll have to use joins like m.wasowski suggests.

提交回复
热议问题