[Python] Iterating through numbers of a 2d array one at a time

Discussão em 'Python' iniciado por Stack, Maio 30, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to iterate through a 2d array, but instead of iterating in rows, I want it to iterate through each number individually. The code currently looks like this:

    import numpy as np
    M = np.array([[1,1,1], [1,1,4], [1,1,1]])
    for row in M[0]:
    print(row, sep=' ')


    This code iterates through each item by row, which is a problem. For example, if I want to use an if statement to check what number it is currently iterating:

    for row in M[0]:
    if row == 1
    print(2)
    else
    print(3)


    It comes up with the error message:

    ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


    I know what this error means, but do not know how I would fix it.

    Continue reading...

Compartilhe esta Página