如何打印格式化为网格的二维列表? [英] How to print out a 2d list that is formatted into a grid?

查看:22
本文介绍了如何打印格式化为网格的二维列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我已经制作了这段代码

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.

推荐答案

如果你想使用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 - - - -
- - - - -
- - - - -

这篇关于如何打印格式化为网格的二维列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆