Reputation: 1157
I have a function in my program that needs to check and make sure that all items in a list (which are all numpy arrays) are equal. The if statement that does this starts with
if np.array_equal(qstatnum[gatnum].count(qstatnum[gatnum][0]), len(qstatnum[gatnum])) == True:
This line gives the error
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I am unsure what the problem is. Any help would be appreciated. Thanks!
Edit: Per request, full if-else statement in code
if np.array_equal(qstatnum[gatnum].count(qstatnum[gatnum][0]), len(qstatnum[gatnum])) == True:
if np.array_equal(qstatnum[gatnum][0], [0,1]) == True:
return qstat
elif np.array_equal(qstatnum[gatnum][0], [1,0]) == True:
return singates[typegat2](qstat)
else:
print("superposition not yet implemented")
else:
return qstat
Apologies for not including, was trying to make the problem as small as possible.
Upvotes: 1
Views: 838
Reputation: 7222
You don't seem to be using array_equal
correctly. The inputs to array_equal
must be arrays, whereas you seem to be passing len
of something, which is a number...
If l1
and l2
are your two lists of arrays, you're probably looking for something like:
if all(np.array_equal(i, j) for i, j in zip(l1, l2)):
# Do something
For example,
>>> l1 = [np.arange(3), np.arange(5)]
>>> l2 = [np.r_[0:3], np.r_[0:5]]
>>> if all(np.array_equal(i, j) for i, j in zip(l1, l2)):
... print('yes')
...
yes
Edit
If you're trying to show that all arrays in your list are equal to each other, then you can just show that all of them are equal to the first:
l = [np.arange(3), np.arange(3), np.arange(3)]
if all(np.array_equal(i, l[0]) for i in l[1:]):
print('All equal!')
Upvotes: 2
Reputation: 37691
As @Praveen already mentioned, it looks like you want to compare two numbers only! If that is the case, then you don't need to use numpy.array_equal()
.
Since, you didn't provide your code, I am unable to explain why you are getting this error. But I am sharing a simple here to let you know what the error means.
Example:
x = np.arange(0, 2, 0.5)
print(x) # [ 0. 0.5 1. 1.5]
y = 2*x
print(y) # [ 0. 1. 2. 3.]
if y <= 1.0:
print ("ok")
This program gives the following error.
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
If you print the value of the boolean expression:
print(y<=1.0)
It prints-
[True True False False]
So, updating the if
condition as follows make the program work.
if np.all(y <= 1.0):
print ("ok")
So, I guess, you can do something like this to solve your problem as well.
if np.all(np.array_equal(qstatnum[gatnum].count(qstatnum[gatnum][0]), len(qstatnum[gatnum]))) == True:
Upvotes: 1
Reputation: 169
I do not have numpy unfortunately, but here is how I would check if all items in a list were equal.
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if arr[i] != arr[j]:
print ("items are not all equal");
Hope that helps.
Upvotes: 0