All elements in the 0'th position of a 2D Array - Python

Viewed 51

So, I am trying to find all the elements in the 0'th position of my 2D array in python. I am wanting to do this in a way as such so that I can iterate through said array. My Array is as such:

board = [["1", "O", "O", "O", "O", "O", "O"],
         ["2", "O", "O", "O", "O", "O", "O"],
         ["3", "O", "O", "O", "O", "O", "O"],
         ["4", "O", "O", "O", "O", "O", "O"],
         ["5", "O", "O", "O", "O", "O", "O"],
         ["6", "O", "O", "O", "O", "O", "O"]]

What I am trying to achieve is the output of ["1", "2", "3", "4"], ["2", "3", "4", "5], ["3", "4", "5", "6"], and so forth for the following columns.

The method that I have tried is as such: print(board[0:4][0]), but this only outputs the very first row of the array: ['1', 'O', 'O', 'O', 'O', 'O', 'O']. Is there any way I could do this as simply or as easily in a single line like the method previously stated?

Thanks in Advance.

4 Answers

Here you go:

fst = [row[0] for row in board]
size = 4
for j in range(len(fst) - size + 1):
    print(fst[j:j+size])

Output

['1', '2', '3', '4']
['2', '3', '4', '5']
['3', '4', '5', '6']

I've removed some of the columns from the board just to make the output tidier. First, you can use zip to iterate over the columns of your board:

board = [["1", "A"],
         ["2", "B"],
         ["3", "C"],
         ["4", "D"],
         ["5", "E"],
         ["6", "F"]]

for column in zip(*board):
    print(column)

Output:

('1', '2', '3', '4', '5', '6')
('A', 'B', 'C', 'D', 'E', 'F')
>>> 

Then, you can add a nested for-loop to iterate over a list of moving / sliding "windows" of each column:

for column in zip(*board):
    for window in [column[i:i+4] for i in range(3)]:
        print(window)

Output:

('1', '2', '3', '4')
('2', '3', '4', '5')
('3', '4', '5', '6')
('A', 'B', 'C', 'D')
('B', 'C', 'D', 'E')
('C', 'D', 'E', 'F')
>>> 

How about to iterate through indexes by using one line for loop ? Just like:

[i[0] for i in board[0:4]]

Some of the other answers are really good. Here is my solution :

board = [["1", "O", "O", "O", "O", "O", "O"],
         ["2", "O", "O", "O", "O", "O", "O"],
         ["3", "O", "O", "O", "O", "O", "O"],
         ["4", "O", "O", "O", "O", "O", "O"],
         ["5", "O", "O", "O", "O", "O", "O"],
         ["6", "O", "O", "O", "O", "O", "O"]]

size = 4
print([[i[0] for i in board[j:j+4]] for j in range(size-1)])

And the output is :

[['1', '2', '3', '4'], ['2', '3', '4', '5'], ['3', '4', '5', '6']]
Related