1

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?

user8953265
  • 21
  • 2
  • 11

3 Answers3

3

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....
Mazdak
  • 105,000
  • 18
  • 159
  • 188
1

The answer by @Kasramvd is excellent and should remain the accepted answer. But here is an answer that is easier to understand, together with some explanation.

for row in zip(*grid):
    print(''.join(row))

One problem you have is that your grid stores things differently than you want to print them. One printout row is not a row in the grid but is rather a column. The standard recipe in Python to swap columns and rows in a 2D list is

zip(*grid)

Basically, the * breaks grid into its individual rows, and zip stitches them together "sideways" in the way we want.

Now that you have printable rows, you need to stitch together the characters in each row into a single string without any delimiters between the characters. Pythons join method for strings will stitch together the characters, and the string showing before the join will be the delimiter. Thus,

''.join(row)

joins your characters together without any delimiter at all.

The rest of my code should be clear to anyone who has learned Python.

Rory Daulton
  • 21,934
  • 6
  • 42
  • 50
0

It's the transpose of the 2d list So

import numpy as np
np.array(grid).T.tolist()

Out:

[['.', '.', '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', '.', '.', '.', '.']]

see https://stackoverflow.com/a/6473727