[Python] For loop with list indexes Python

Discussão em 'Python' iniciado por Stack, Setembro 3, 2025.

  1. Stack

    Stack Membro Participativo

    I have this code that is supposed to print each item in the main list on a new row with a corresponding row number. In the below code it works fine:

    my_list = [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]
    for item in my_list:
    print(my_list.index(item)+1, item)


    However when I try to implement it into a "tic-tac-toe" game I'm making it doesn't work.

    Here is the problematic code:

    def showGrid(y, x, "X"):
    board[y][x] = "X"
    print(" x x x")
    for row in board:
    print(board.index(row)+1, sub("[,']", "", str(row)[1:-1]))


    The output of the code above is not the same as the first example and instead it gives a random output depending on what the y and x values are.

    For example if y and x were both set to 1 the output is:

    x x x
    1 X - -
    2 - - -
    2 - - -


    And when x and y are both set to 2 the output is:

    x x x
    1 - - -
    2 - X -
    1 - - -


    What I want it to be is 1 2 3 going down.

    If there is a page that covers this please link it. If more of the code is needed please say so. Otherwise thanks in advance. :)

    Continue reading...

Compartilhe esta Página