0

I have a 2D numpy array (400x400) and while there are zeros in this array I want to run a while loop until after a few iterations they are all removed. So in the while block I remove some of the zeros in every iteration. From here I have the code snipped to check if there are still zeros in my array:

check = 0 in array

This returns either a 'True' or a 'False' and is working. Now I want to use this in the beginning of the while-loop and I expected it to work like the following:

while 0 in array == True:
    'do sth.'

Instead I get the following error:

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

I can make a workaround where in the end of every while-loop I write the result of 'check = 0 in array' into another variable and check this variable in the beginning of the while loop, but I think there should be a better way.

riyansh.legend
  • 117
  • 1
  • 13

2 Answers2

0

If I understand your question right, this is want you want:

array = [[20,0],[11, 1]]
count = 0 
while count < len(array): 
    if 0 in array[count]: 
        print("Found zero")
    count += 1

Output:

[20, 0]
Found zero
[11, 1]
loxosceles
  • 347
  • 5
  • 21
  • In my case it is not important to count the zeros. The aim was to keep the while loop going as long as there are zeros in the array. Then in the loop these zeros are removed in several iteration steps. – riyansh.legend Feb 02 '20 at 09:18
  • My code snippet is not counting the zeros. The `count` variable ensures that the loop is running until the end (stop-condition). The `print` statement is a placeholder for whatever you want to do with the current array element (sublist). If you don't want to use a `count` variable you also implement this as a nested `for` loop. – loxosceles Feb 02 '20 at 09:22
0

Python parses this as

while 0 in (array==True):

where of course you mean

while (0 in array) == True:

which however of course is better written

while 0 in array:

Python's flow-control conditionals already implicitly convert every expression into a "truthiness" value which is either True or False. See further What is Truthy and Falsy? How is it different from True and False?

tripleee
  • 175,061
  • 34
  • 275
  • 318