Python:如何打印出格式化为网格的二维列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22584652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:12:37  来源:igfitidea点击:

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

pythonlist2d

提问by user3225528

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.

但是,我不确定从哪里开始。

回答by m.wasowski

Use string join()

使用字符串 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))

回答by Christian

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

如果要使用 的结果grid_maker(),则必须使用 返回其结果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.

我修改了它,因为我不认为每个元素都必须在另一个list.

To print the "grid", you could iterate through each rowand 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 - - - -
- - - - -
- - - - -

回答by anana

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

如果您想在自己的行上“漂亮”地打印每个子列表的网格,您可以使用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.

它仍然会将每个元素显示为一个列表,正如您定义的那样,如果您想将它们显示为字符串,则必须使用 m.wasowski 建议的连接。