List printing is not working as needed. Pattern made is 90 degree anti-clockwise

Viewed 59

So I want to print this list with many sub lists:

grid = [['.', '.', '.', '.', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['.', 'O', 'O', 'O', 'O', 'O'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['.', '.', '.', '.', '.', '.']]

y_coord = 0

for i in grid:
    print(*grid[:][y_coord])
    y_coord += 1

The expected output is:

..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....

But the actual output is:

. O O . . .
O O O O . .
O O O O O .
. O O O O O
O O O O O .
O O O O . .
. O O . . .
. . . . . .
3 Answers

You need to rotate the array to get the columns instead of rows as you are doing now. You can use zip() to transpose your array. Then just join() and print:

grid = [['.', '.', '.', '.', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['.', 'O', 'O', 'O', 'O', 'O'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['.', '.', '.', '.', '.', '.']]


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

Prints:

..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....
grid = [['.', '.', '.', '.', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['.', 'O', 'O', 'O', 'O', 'O'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['.', '.', '.', '.', '.', '.']]

for x in range(0, len(grid[0])):
    print(*[y[x] for y in grid], sep='')

Output


enter image description here

The other answers show you how to fix the array, but don't explain what you're doing wrong. Let's take a look at your indexing expression

print(*grid[:][y_coord])

For python sequences, the index [:] generally means to make a copy of the container that points to the same data. For a list, like grid, it's equivalent to list(grid). Notice that the nested lists are the same. So what you're really doing is the same as

print(*grid[y_coord])

Hopefully it's clear that this just prints the contents of the list line by line.

You can either pre-transpose the entire list as @Mark suggests, or select elements from the correct column of each nested sublist as @Алексей Р suggests.

Your original notation is evocative of numpy. If grid were a 2D numpy array, you could index it as grid[:, y_coord] to get the transpose. If you tried indexing a numpy array with the original double index, to you would get the same incorrect results for the same reason explained in the first paragraph.

Related