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

天大地大妈咪最大 提交于 2019-12-01 22:00:36

问题


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

>>>grid_maker(3,5) => [[['o'], ['-'], ['-'], ['-'], ['-']], [['-'], ['-'], ['-'], ['-'], ['-']], [['-'], ['-'], ['-'], ['-'], ['-']]] 

I want to make another function that will take in the produced 2d array and print it out such that it is in this format:

o----
-----
----- 

However, I am unsure where to start.


回答1:


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.




回答2:


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 - - - -
- - - - -
- - - - -



回答3:


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))


来源:https://stackoverflow.com/questions/22584652/python-how-to-print-out-a-2d-list-that-is-formatted-into-a-grid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!