Reputation: 1665
I have function that prints an array:
In [93]:
printArr(arrs[0], Nrows, Ncols)
# # #
# # #
# # #
O O O
O O O
O O O
Where in the printArr function I add a comma (,) to the end of that function's call to pythons print function to get the output in 3 columns.
BUT, what if I want to make several calls to printArr, and have the output stacked to the columns, like this?
# # # O O O
# # # # # #
# # # # # #
O O O O O O
O O O O O O
O O O O O O
Two calls to printArr just gives me this
In [96]:
printArr(arrs[0], Nrows, Ncols)
print " "
printArr(arrs[1], Nrows, Ncols)
# # #
# # #
# # #
O O O
O O O
O O O
O O O
# # #
# # #
# # #
O O O
O O O
Is there a way to accomplish this, or do I have to redo my entire printArr function?
Thanks
EDIT: Okay, here is my printArr function
def printArr(arr, Nrows, Ncols):
for row in range(0, Nrows):
for col in range(0, Ncols):
if arr[row][col] == 1:
print '#',
else:
print 'O',
print " "
It takes an 3-dimensional Ndarray as input, and I intened to use that function to print all the matrices in that array in a nice way (for example with 3 total columns and 3 total rows)
Thanks again
Upvotes: 2
Views: 93
Reputation: 20005
You could create a row generator and use it in your print functions:
def rows(arr):
for row in arr:
yield " ".join('#' if c == 1 else 'O' for c in row)
def printArr(arr):
print "\n".join(rows(arr))
from itertools import izip_longest
def print2Arr(arr1, cols1, arr2, cols2):
for row1, row2 in izip_longest(rows(arr1), rows(arr2)):
row1 = row1 or " " * (2 * cols1 - 1)
row2 = row2 or " " * (2 * cols2 - 1)
print row1 + " " + row2
Examples:
>>> arr1 = [[1, 0, 0], [1, 1, 0]]
>>> arr2 = [[1, 0, 0], [1, 1, 0], [1, 0, 0]]
>>> printArr(arr1)
# O O
# # O
>>> print2Arr(arr1, 3, arr2, 3)
# O O # O O
# # O # # O
# O O
>>> print2Arr(arr2, 3, arr1, 3)
# O O # O O
# # O # # O
# O O
Upvotes: 0
Reputation: 926
def printArrays(listOfArrays,cols):
splittedArrays = [[array[x:x+cols] for x in range(0,len(array),cols)] for array in listOfArrays]
c = list(zip(*splittedArrays))
c = ["".join([[" "+"".join(y)][0]for y in x]) for x in c]
print("\n".join([" ".join(array) for array in c]))
a =["a","b","c","a","b","c"]
b= ["x","y","z","x","y","z"]
printArrays([a,b],3)
printArrays([a,b],2)
Upvotes: 1