打印任意大小列表的项目

时间:2015-09-04 13:45:02

标签: python list function

我有这段代码:

def draw_grid(grid_ref):
    for i in grid_ref:
        print i[0], i[1], i[2], i[3], i[4], i[5]

y0 = ['-','-','-','-','-','-']
y1 = ['-','-','-','-','-','-']
y2 = ['-','-','-','-','-','-']
y3 = ['-','-','-','-','-','-']
y4 = ['-','-','-','-','-','-']
y5 = ['-','-','-','-','-','-']
grid = [y0,y1,y2,y3,y4,y5]
draw_grid(grid)

哪个输出是:

- - - - - -
- - - - - -
- - - - - -
- - - - - -
- - - - - -
- - - - - -

这就是我想要的,但却有些不对劲。主要问题是我无法使用更大或更小网格的draw_grid函数。所以我有:

def grid_gen(x,y):    #Generates a grid of y lists with x items in every list
    row = []
    grid = []
    for i in range(x):
        row.append('-')
    for i in range(y):
        grid.append(row)
    return grid

我无法使用draw_grid

我的问题是:我如何改进draw_grid功能以适应任何类型的网格并获得相同的输出?

3 个答案:

答案 0 :(得分:3)

您可以使用' '.join从网格中连接整个线条并打印它,而不管它有多少个单元格。

def draw_grid(grid_ref):
    for i in grid_ref:
        print(' '.join(i))

此外,正如评论中所述,您的grid_gen函数将创建一个列表列表,其中包含对相同列表的多个引用,即如果您更改其中一个,则更改他们都是。在将[:]列表插入row列表之前,您可以使用grid创建def grid_gen(x,y): row = [] grid = [] for i in range(x): row.append('-') for i in range(y): grid.append(row[:]) return grid 列表的副本。

def grid_gen(x,y):
    return [['-' for i in range(x)] for k in range(y)]

或者更短,使用嵌套列表理解:

arecord

答案 1 :(得分:3)

您还可以使用print()功能:

from __future__ import print_function  # Python 2.x

def draw_grid(grid_ref):
    for i in grid_ref:
        print(*i)

默认分隔符为' '

答案 2 :(得分:0)

尝试字符串乘法:

>>> n = 5
>>> for x in range(n):
...     print ('- '*n).strip()
... 
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
>>> n =2
>>> for x in range(n):
...     print ('- '*n).strip()
... 
- -
- -
>>>