Python:如何打印格式化为网格的二维列表? [英] Python: how to print out a 2d list that is formatted into a grid?
本文介绍了Python:如何打印格式化为网格的二维列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前,我已经编写了这段代码
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'], ['-'], ['-'], ['-'], ['-']], [['-'], ['-'], ['-'], ['-'], ['-']], [['-'], ['-'], ['-'], ['-'], ['-']]]
我想制作另一个函数,该函数将采用产生的2d数组并将其打印出来,使其具有以下格式:
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.
推荐答案
如果要使用grid_maker()
的结果,则必须使用return
:
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
我修改了它,因为我不认为每个元素都必须在另一个list
内部.
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
输出:
print_grid(grid_maker(3, 5))
o - - - -
- - - - -
- - - - -
这篇关于Python:如何打印格式化为网格的二维列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文