2

我在 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
4

5 回答 5

2

像这样的东西:

>>> 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
于 2013-05-14T11:31:46.877 回答
2
>>> 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

我想你会知道如何打印第一行:)

于 2013-05-14T11:29:14.710 回答
1

此功能与您的确切输出相匹配。

>>> 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
于 2013-05-14T11:36:01.867 回答
0
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
于 2014-01-10T15:54:03.450 回答
0

用于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
于 2022-02-08T12:59:39.097 回答