There is always the easy way.
import numpy as np
print(np.matrix(A))
Answer from Souradeep Nanda on Stack OverflowThere is always the easy way.
import numpy as np
print(np.matrix(A))
A combination of list comprehensions and str joins can do the job:
inf = float('inf')
A = [[0,1,4,inf,3],
[1,0,2,inf,4],
[4,2,0,1,5],
[inf,inf,1,0,3],
[3,4,5,3,0]]
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in A]))
yields
0 1 4 inf 3
1 0 2 inf 4
4 2 0 1 5
inf inf 1 0 3
3 4 5 3 0
Using for-loops with indices is usually avoidable in Python, and is not considered "Pythonic" because it is less readable than its Pythonic cousin (see below). However, you could do this:
for i in range(n):
for j in range(n):
print '{:4}'.format(A[i][j]),
print
The more Pythonic cousin would be:
for row in A:
for val in row:
print '{:4}'.format(val),
print
However, this uses 30 print statements, whereas my original answer uses just one.
python - How to print a 2D array in a "pretty" format? - Stack Overflow
Print a 2D array in a certain way in Python - Stack Overflow
python - How can I print a 2d array in different ways - Stack Overflow
how to print 2D array in python - Stack Overflow
Are 2D arrays memory-efficient in Python?
What are the challenges when working with 2D arrays?
Videos
Your string formatting is wrong %s is for string your i and j are integers so use %d
So use:
locate[i][j]='%d%d'%(i,j)
Further, to print in matrix format the full code would be:
for i in range(10):
s=''
for j in range(10):
locate[i][j] = '%d,%d'%(i,j)
s+=locate[i][j]+' '
print s
for i in range(10):
for j in range(10):
print(locate[i][j])`
This should make it work.
Here is what your are using:
def printArray(a):
for row in range(len(a[0])):
for col in range (len(a[0])):
b = print("{:8.3f}".format(a[row][col]), end = " ")
print(b)
You are using two for loops with len(a[0]) but your input data isn't a square, so that can't work!
You might consider using this:
def printA(a):
for row in a:
for col in row:
print("{:8.3f}".format(col), end=" ")
print("")
That will give you this:
In [14]: a = [[1, 2, 1, 2], [3, 4, 5, 3], [8, 9, 4, 3]]
In [15]: printA(a)
1.000 2.000 1.000 2.000
3.000 4.000 5.000 3.000
8.000 9.000 4.000 3.000
In [16]: b = [[1, 2, 1, 2, 5], [3, 4, 7, 5, 3], [8, 2, 9, 4, 3], [2, 8, 4, 7, 6]]
In [17]: printA(b)
1.000 2.000 1.000 2.000 5.000
3.000 4.000 7.000 5.000 3.000
8.000 2.000 9.000 4.000 3.000
2.000 8.000 4.000 7.000 6.000
There are three main issues with the code you have posted: the way of iterating through the array, the assignment of the b variable to a the return of a print statement, and the printing of that b variable.
Firstly, the way you are iterating through the array is fairly counter-intuitive. You can simply use
def printArray(arr):
for row in arr:
for item in row:
# code for printing
to make it much more clear.
Secondly, your understanding of the print statement seems to be a bit lacking. The print statement takes in an argument and prints it out directly, so there is no need to assign it to a variable. Since the print statement has no official return, it automatically returns None, which ties in with the next point to explain the Nones at the end of your print statements.
Finally, the printing of the b variable which has a value None assigned to it as discussed above produces the Nones you see.
To fix your code, you could use the following solution.
a = [[1,2,1,2], [3,4,5,3], [8,9,4,3]]
def printArray(arr):
for row in arr:
for item in row:
print("{:8.3f}".format(item), end = " ")
print("")
printArray(a)
Other than the things stated above, this code differs by adding a print(""), which is equivalent to a new line, after every row in the array.
This is happening because you're printing the Matrix that contains the Squares. This calls the __str__() for the Matrix class. If you haven't defined a __str__() for that class that returns a string comprising the str() of each of its contained objects, it'll give you the repr() of each of those objects, as defined by their __repr__(). I don't suppose you've defined one. The default is a mere memory location, as you see.
Here's a demo with a stub class:
>>> class A:
... def __str__(self):
... return 'a'
... def __repr__(self):
... return 'b'
...
>>> print(A())
a
>>> A()
b
>>> [A(), A()]
[b, b]
>>> print([A(), A()])
[b, b]
>>> print(*[A(), A()])
a a
The solution is to either define a specific __str__() for Matrix that returns the str() for each of its contained objects, or define a suitable __repr__() for the Square objects (which should be something that could be passed to eval() to recreate the object, not just something like "KN").
You should use __repr__
difference between __repr__ and __str__
class A():
def __str__(self):
return "this is __str__"
class B():
def __repr__(self):
return "this is __repr__"
a = [A() for one in range(10)]
b = [B() for one in range(10)]
print a
[<__main__.A instance at 0x103e314d0>, <__main__.A instance at 0x103e31488>]
print b
[this is __repr__, this is __repr__]
I would use *, the unpacking operator:
array_2d = [[1, 2, 3], [10, 20, 30], [100, 200, 300]]
for row in array_2d:
print(*row, sep="\t")
#output:
1 2 3
10 20 30
100 200 300
This will work for any size of array with any type of values:
print('\n'.join(' '.join(str(x) for x in row) for row in values))
Somewhat longer and much clearer:
lines = []
for row in values:
lines.append(' '.join(str(x) for x in row))
print('\n'.join(lines))
Your list is initialized incorrectly.
It should be like:
array = [[None for _ in range(cols)] for _ in range(rows)]
which means create rows number of list where each row list has cols elements.
When initializing an array, the inner array specifies the columns and the outer specifies the rows, like so:
array = [[None for x in range(cols)] for y in range(rows)]
Complete Code:
rows = 7
cols = 6
array = [[None for x in range(cols)] for y in range(rows)]
for i in range(rows):
for j in range(cols):
array[i][j] = " 0 "
for k in range(rows):
for l in range(cols):
print(array[k][l], end='')
print("")