I have a list given:
grid = [['.', '.', '.', '.', '.', '.'],
['.', '0', '0', '.', '.', '.'],
['0', '0', '0', '0', '.', '.'],
['0', '0', '0', '0', '0', '.'],
['.', '0', '0', '0', '0', '0'],
['0', '0', '0', '0', '0', '.'],
['0', '0', '0', '0', '.', '.'],
['.', '0', '0', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
and I want to print it like this:
..00.00..
.0000000.
.0000000.
..00000..
...000...
....0....
I tried it with the following code but it will give me always a
i = 0
j = 0
while i < len(grid):
while j < len(grid[j]):
if i == len(grid)-1:
print(grid[i][j])
j = j + 1
else:
print(grid[i][j], end='')
i = i + 1
IndexError: list index out of range
What can I do?
You want the columns so use zip
to get the columns then concatenate the items using str.join()
method within a list comprehension to form the lines and finally join the lines with new-line characters.:
In [89]: print('\n'.join([''.join(c) for c in zip(*grid)]))
..00.00..
.0000000.
.0000000.
..00000..
...000...
....0....