Search code examples
pythonpython-3.xenumerate

Using enumerate to find the index of a str in my array


I am creating a simple game grid. I want to be able to find the location of a player's piece to work out their next move. I have tried using enumerate but it does not find anything and I cannot figure out my error. Any suggestions would be welcome.

def createBoard():
    startBoard=[]
    for x in range(0,12):
        startBoard.append(["_"] * 5)
    startBoard[11][1]= 'P1'
    startBoard[11][2]= 'P2'
    startBoard[11][3]= 'P3'
    startBoard[11][4]= 'P4'
    return startBoard

def print_board(board):
        for row in board:
            print (" ".join(row))
        return True


def findBoardLocation(board,a):
    for i in [i for i,x in enumerate(board) if x == a]:
       print('location of {0} is [{1}]'.format(a,i))

startBoard=createBoard()
print_board(startBoard)
a='P1'
findBoardLocation(startBoard,a)

I don't know if enumerate is the right option to use as I need to know just the row, the column is not really necessary. Thanks


Solution

  • You are looping over just the nested rows; you are not looping over the columns.

    Your list structure looks like:

    [['_', '_', '_', '_', '_'],
     ['_', '_', '_', '_', '_'],
     # ...
    ]
    

    but you only loop over the outer list. This makes x reference a whole list; 'P1' is never going to be equal to ['_', 'P1', 'P2', 'P3', 'P4']. You'll have to loop over the inner list too:

    def findBoardLocation(board, a):
        for rowid, row in enumerate(board):
           for colid, column in enumerate(row):
               if column == a:
                   print('location of {0} is [{1}][{2}]'.format(a, rowid, colid))