[Python] How to vectorize a function within loop with break in Python 3 [closed]

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

  1. Stack

    Stack Membro Participativo

    I am trying to run the following program with numpy vector code within loop with break in Python 3 but get ValueError: The truth value of an array with more than one element is ambiguous because of the "if" (it's ok to compare a numpy array to a scalar as each element is compared to the scalar) How would this be possible to run it in a vectorized way ? The issue is managing the break within the loop.

    Below a dummy program:

    import numpy as np

    THRESHOLD=0.5
    ARRAY_LEN =10

    def inner_compute():
    pass

    def compute(draws):
    return draws /2

    calculation = np.zeros(ARRAY_LEN)
    for i in range(5):
    draws = np.random.uniform(0, 1, ARRAY_LEN)
    if draws < THRESHOLD:
    # if above ^ creates a ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
    calculation += compute(draws)
    break
    #use np.vectorize and call inner_compute?

    print (f"calculation {calculation}")

    Continue reading...

Compartilhe esta Página