首页 > 解决方案 > Check if array is in deque of arrays? Python

问题描述

I have the following code:

   def getEmptySquares(self):
        emptySquares=deque([])
        for i in range(self.grid.shape[0]):
            for j in range(self.grid.shape[1]):
                if np.array([i,j]) not in dequeList:
                    emptySquares.append(np.array([i,j]))
        print(emptySquares)

where the grid is a numpy array.

An example of the dequeList variable is:

deque([array([5, 7]), array([6, 7]), array([6, 6]), array([6, 5]), array([6, 4]), array([5, 4])])

I get the following error when I run this function:

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

Why is this happening?

标签: pythonerror-handlingdequevalueerror

解决方案


The issue you're running into here is that numpy does not define __eq__ for np.arrays as a comparison, but rather a method to construct a "logical" array.

Consider the array:

some_array = np.array([1, 2, 3, 4])

What do you expect the value of some_array == some_array will be? Usually in Python, we would expect it to be True, but this is not the case in numpy:

>>> some_array == some_array
array([True,  True, True, True])

Instead of boolean, using == with np.arrays produces another np.array. If we try to treat this array like a boolean, we get the error you encountered:

>>> bool(some_array)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

This error pops up here since checking whether or not an object is contained in a collections.deque involves iterating over the deque and comparing each element to the object in question. At each step, python calls the np.array.__eq__ method, and then "gets confused" when it receives an array instead of a bool.

To mitigate this, you need to manually search the deque for the array in question rather than relying on the in operator. This can be accomplished by applying the any builtin to a generator which performs the element-wise comparisons:

new_array = np.array([i,j])
if not any((new_array == elem).all() for elem in dequeList)):
   ...

推荐阅读