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.
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]
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?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.