0

I'm trying to print a matrix with user assigned variable for the length and width, but have used manual assignment for easier reading. Right now my output doesn't include any new lines, but that is what I'm attempting to do.

def matrix(rows,cols):
    grid = [[0 for i in range(cols)] for i in range(rows)]
    return grid

rows = 5
cols = 5
print(matrix(rows,cols))

Is it possible to insert a print("\n") statement into the for statement to properly print out the matrix. Currently the output is as follows:

[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

Desired output:

[[0, 0, 0, 0, 0], 
 [0, 0, 0, 0, 0], 
 [0, 0, 0, 0, 0], 
 [0, 0, 0, 0, 0], 
 [0, 0, 0, 0, 0]]
4

2 回答 2

4

这恰好是pprint的确切行为。

from pprint import pprint

def matrix(rows,cols):
    grid = [[0 for i in range(cols)] for i in range(rows)]
    return grid

rows = 5
cols = 5
pprint(matrix(rows,cols))
于 2013-11-11T04:22:05.453 回答
0

pprint 做你需要的很好,但你不应该为你的矩阵类型使用一个类吗?使用裸列表可能会在以后咬你。

于 2013-11-11T04:24:07.437 回答