带有索引的打印矩阵python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16541973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:57:11  来源:igfitidea点击:

print matrix with indicies python

pythonprintingmatrix

提问by user1692261

I have a matrix in Python defined like this:

我在 Python 中有一个矩阵定义如下:

matrix = [['A']*4 for i in range(4)]

How do I print it in the following format:

我如何以以下格式打印它:

   0  1  2  3
0  A  A  A  A
1  A  A  A  A
2  A  A  A  A
3  A  A  A  A

采纳答案by Sukrit Kalra

This function matches your exact output.

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

>>> 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

To check for single length elements and put an &in place of elements with length > 1, you could put a check in the list comprehension, the code would change as follows.

要检查单个长度的元素并&替换长度 > 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

回答by icecrime

>>> 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

I guess you'll find out how to print out the first line :)

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

回答by Ashwini Chaudhary

Something like this:

像这样的东西:

>>> 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

回答by Muhammed Rafi CH

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='')

it will print like this:

它会像这样打印:

A A A A
A A A A
A A A A
A A A A