There are a lot of ways. Probably a str.join of a mapping of str.joins:
>>> a = [['1','2','3'],
... ['4','5','6'],
... ['7','8','9']]
>>> print('\n'.join(map(''.join, a)))
123
456
789
>>>
Answer from juanpa.arrivillaga on Stack OverflowThere are a lot of ways. Probably a str.join of a mapping of str.joins:
>>> a = [['1','2','3'],
... ['4','5','6'],
... ['7','8','9']]
>>> print('\n'.join(map(''.join, a)))
123
456
789
>>>
Best way in my opinion would be to use print function. With print function you won't require any type of joining and conversion(if all the objects are not strings).
>>> a = [['1','2','3'],
... ['4', 5, 6], # Contains integers as well.
... ['7','8','9']]
...
>>> for x in a:
... print(*x, sep='')
...
...
123
456
789
If you're on Python 2 then print function can be imported using from __future__ import print_function.
matrix = [[1,2,3], [4,5,6]]
How do I print this as 1 2 3
4 5 6
Thanks in advance!
To make things interesting, let's try with a bigger matrix:
matrix = [
["Ah!", "We do have some Camembert", "sir"],
["It's a bit", "runny", "sir"],
["Well,", "as a matter of fact it's", "very runny, sir"],
["I think it's runnier", "than you", "like it, sir"]
]
s = [[str(e) for e in row] for row in matrix]
lens = [max(map(len, col)) for col in zip(*s)]
fmt = '\t'.join('{{:{}}}'.format(x) for x in lens)
table = [fmt.format(*row) for row in s]
print '\n'.join(table)
Output:
Ah! We do have some Camembert sir
It's a bit runny sir
Well, as a matter of fact it's very runny, sir
I think it's runnier than you like it, sir
UPD: for multiline cells, something like this should work:
text = [
["Ah!", "We do have\nsome Camembert", "sir"],
["It's a bit", "runny", "sir"],
["Well,", "as a matter\nof fact it's", "very runny,\nsir"],
["I think it's\nrunnier", "than you", "like it,\nsir"]
]
from itertools import chain, izip_longest
matrix = chain.from_iterable(
izip_longest(
*(x.splitlines() for x in y),
fillvalue='')
for y in text)
And then apply the above code.
See also http://pypi.python.org/pypi/texttable
For Python 3 without any third part libs:
matrix = [["A", "B"], ["C", "D"]]
print('\n'.join(['\t'.join([str(cell) for cell in row]) for row in matrix]))
Output
A B
C D
def print_grid(grid)
for row in grid:
print(' '.join(row))
Or even better, pprint.pprint
This should work no matter how many items are present in the grid, as long as it is 2-dimensional.
grid=[['X','X','O'],['X','O','X'],['O','X','X']]
def print_grid(grid):
for item in grid:
line = ' '.join(item)
print(line)