Ted Ted - 26 days ago 28
Python Question

Print labels for rows and columns in grid (PYTHON)

I apologize if this question has been posted before, however if it was, I was not able to find it anywhere. Also, I am not familiar with numpy. Unfortunately the only answers I could find were numpy aswers. I would prefer not to use numpy as I am still learning the basics of coding/python.

I am trying to print out labels for my grid. I have a simple game board, and I would like to label the columns A,B,C,D and the rows 1,2,3,4.

Here is my code that generates the grid:


def initial(): #Function that creates the 2d array and assigns it the values I want
board = []
for x in range(numrows):
board.append([])
for y in range(numcols):
if ((x + y)%2):
board[x].append('X')
else:
board[x].append('O')



Here is the output:


O X O X
X O X O
O X O X



I am trying to make my output look like this:


A B C D
1 O X O X
2 X O X O
3 O X O X



I know that I have to manipulate the indexes, not the values, but like I said, I'm still a noob. What would be the best way to go about this based on what I have here? Should it be separate for loops and print statements than the code that makes the initial grid? Or can I somehow alter my initial game board code to implement these row/column labels?

So far, I have the idea of doing something like this:


for r in range(numrows): # I have a variable in the code numrows = 3
if(r==0):
print("1")
if(r==1):
print("2")
if(r==2):
print("3")
for c in range(numcols): # also a variable numcols = 4
if(c==0):
print("A")
if(c==1):
print("B")
if(c==2):
print("C")
if(c==3):
print("D")
show_grid(board) #function that prints my board



I think I am close, however am at my wits end.. I need help. Thanks in advance for the time and effort taken to answer my question.

Answer

For something modular (hence Pythonic :p):

columnsIndices = ['A', 'B', 'C', 'D']
rowsIndices = [1, 2, 3, 4]
print(" ", end="")
for c in columnsIndices :
    print(" " + str(c), end="")      #str() is useless, but it's good practice
print()                              #linefeed
for i in range(len(grid)) :
    print(str(rowsIndices[i]), end="")
    for elt in grid[i] :
        print(" " + str(elt), end="")
    print()                          #linefeed
Comments