我在 Python 中定义了一个矩阵,如下所示:
matrix = [['A']*4 for i in range(4)]
如何按以下格式打印:
0 1 2 3
0 A A A A
1 A A A A
2 A A A A
3 A A A A
像这样的东西:
>>> matrix = [['A'] * 4 for i in range(4)]
>>> def solve(mat):
print " ", " ".join([str(x) for x in xrange(len(mat))])
for i, x in enumerate(mat):
print i, " ".join(x) # or " ".join([str(y) for y in x]) if elements are not string
...
>>> solve(matrix)
0 1 2 3
0 A A A A
1 A A A A
2 A A A A
3 A A A A
>>> matrix = [['A'] * 5 for i in range(5)]
>>> solve(matrix)
0 1 2 3 4
0 A A A A A
1 A A A A A
2 A A A A A
3 A A A A A
4 A A A A A
>>> for i, row in enumerate(matrix):
... print i, ' '.join(row)
...
0 A A A A
1 A A A A
2 A A A A
3 A A A A
我想你会知道如何打印第一行:)
此功能与您的确切输出相匹配。
>>> def printMatrix(testMatrix):
print ' ',
for i in range(len(testMatrix[1])): # Make it work with non square matrices.
print i,
print
for i, element in enumerate(testMatrix):
print i, ' '.join(element)
>>> matrix = [['A']*4 for i in range(4)]
>>> printMatrix(matrix)
0 1 2 3
0 A A A A
1 A A A A
2 A A A A
3 A A A A
>>> matrix = [['A']*6 for i in range(4)]
>>> printMatrix(matrix)
0 1 2 3 4 5
0 A A A A A A
1 A A A A A A
2 A A A A A A
3 A A A A A A
要检查单个长度元素并&
替换长度 > 1 的元素,您可以在列表推导中进行检查,代码将更改如下。
>>> def printMatrix2(testMatrix):
print ' ',
for i in range(len(testmatrix[1])):
print i,
print
for i, element in enumerate(testMatrix):
print i, ' '.join([elem if len(elem) == 1 else '&' for elem in element])
>>> matrix = [['A']*6 for i in range(4)]
>>> matrix[1][1] = 'AB'
>>> printMatrix(matrix)
0 1 2 3 4 5
0 A A A A A A
1 A AB A A A A
2 A A A A A A
3 A A A A A A
>>> printMatrix2(matrix)
0 1 2 3 4 5
0 A A A A A A
1 A & A A A A
2 A A A A A A
3 A A A A A A
a=[["A" for i in range(4)] for j in range(4)]
for i in range(len(a)):
print()
for j in a[i]:
print("%c "%j,end='')
它会像这样打印:
A A A A
A A A A
A A A A
A A A A
用于pandas
显示任何带有索引的矩阵:
>>> import pandas as pd
>>> pd.DataFrame(matrix)
0 1 2 3
0 A A A A
1 A A A A
2 A A A A
3 A A A A