Saadat - 1 year ago 77
Python Question

# Pretty Printing (2D Arrays, Box)

I have written the following code:

``````for row in range(len(listOfLists)):
print('+' + '-+'*len(listOfLists))
print('|', end='')
for col in range(len(listOfLists[row])):
print(listOfLists[row][col], end='|')
print(' ') #To change lines
print('+' + '-+'*len(listOfLists))
``````

Input:

``````[['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i'],
['j', 'k', 'l']]
``````

Output:

``````+-+-+-+-+
|a|b|c|
+-+-+-+-+
|d|e|f|
+-+-+-+-+
|g|h|i|
+-+-+-+-+
|j|k|l|
+-+-+-+-+
``````

Desired Output:

``````+-+-+-+
|a|b|c|
+-+-+-+
|d|e|f|
+-+-+-+
|g|h|i|
+-+-+-+
|j|k|l|
+-+-+-+
``````

Which prints a '+-+' around the elements of the 2D array.
However, my code only works for a square array (n^2).

How can I generalise it so that it works for any variation of array (as long as all lists are equal length)

Thank you

Your problem was that `len(listOfLists)` was used for the size of the printed table in both directions. `len(listOfLists)` defaults to number of rows, by doing `len(listOfLists[1])` you get the number of columns.

`````` listOfLists = [['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i'],
['j', 'k', 'l']]

for row in range(len(listOfLists)):
print('+' + '-+'*len(listOfLists[0]))
print('|', end='')
for col in range(len(listOfLists[row])):
print(listOfLists[row][col], end='|')
print(' ') #To change lines
print('+' + '-+'*(len(listOfLists[0])))
``````

output:

``````+-+-+-+
|a|b|c|
+-+-+-+
|d|e|f|
+-+-+-+
|g|h|i|
+-+-+-+
|j|k|l|
+-+-+-+
``````

Happy coding!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download