检查数组是否在数组的双端队列中? Python
Check if array is in deque of arrays? Python
我有以下代码:
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)
其中网格是一个 numpy 数组。
dequeList 变量的一个例子是:
deque([array([5, 7]), array([6, 7]), array([6, 6]), array([6, 5]), array([6, 4]), array([5, 4])])
当我 运行 这个函数时,我得到以下错误:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
为什么会这样?
您 运行 遇到的问题是 numpy 没有为 np.array
定义 __eq__
作为比较,而是一种构造 "logical"数组。
考虑数组:
some_array = np.array([1, 2, 3, 4])
您期望 some_array == some_array
的值是多少?通常在 Python 中,我们会期望它是 True
,但在 numpy 中并非如此:
>>> some_array == some_array
array([True, True, True, True])
将 ==
与 np.array
一起使用会生成另一个 np.array
,而不是布尔值。如果我们尝试将此数组视为布尔值,则会出现您遇到的错误:
>>> 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()
这里会出现这个错误,因为检查对象是否包含在 collections.deque
中涉及遍历 deque
并将每个元素与相关对象进行比较。在每个步骤中,python 调用 np.array.__eq__
方法,然后在接收到数组而不是 bool
.
时调用 "gets confused"
为了缓解这种情况,您需要手动搜索 deque
以查找有问题的数组,而不是依赖 in
运算符。这可以通过将 any
内置函数应用于执行逐元素比较的生成器来实现:
new_array = np.array([i,j])
if not any((new_array == elem).all() for elem in dequeList)):
...
我有以下代码:
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)
其中网格是一个 numpy 数组。
dequeList 变量的一个例子是:
deque([array([5, 7]), array([6, 7]), array([6, 6]), array([6, 5]), array([6, 4]), array([5, 4])])
当我 运行 这个函数时,我得到以下错误:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
为什么会这样?
您 运行 遇到的问题是 numpy 没有为 np.array
定义 __eq__
作为比较,而是一种构造 "logical"数组。
考虑数组:
some_array = np.array([1, 2, 3, 4])
您期望 some_array == some_array
的值是多少?通常在 Python 中,我们会期望它是 True
,但在 numpy 中并非如此:
>>> some_array == some_array
array([True, True, True, True])
将 ==
与 np.array
一起使用会生成另一个 np.array
,而不是布尔值。如果我们尝试将此数组视为布尔值,则会出现您遇到的错误:
>>> 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()
这里会出现这个错误,因为检查对象是否包含在 collections.deque
中涉及遍历 deque
并将每个元素与相关对象进行比较。在每个步骤中,python 调用 np.array.__eq__
方法,然后在接收到数组而不是 bool
.
为了缓解这种情况,您需要手动搜索 deque
以查找有问题的数组,而不是依赖 in
运算符。这可以通过将 any
内置函数应用于执行逐元素比较的生成器来实现:
new_array = np.array([i,j])
if not any((new_array == elem).all() for elem in dequeList)):
...