I have a matrix in Python defined like this:
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
解决方案
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,
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.
>>> def printMatrix2(testMatrix):
print ' ',
for i in range(len(testmatrix[1])):
print i,
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