python - 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?
解决方案
The issue you're running into here is that numpy does not define __eq__
for np.array
s 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.array
s 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)):
...
推荐阅读
- javascript - 无法为特定的导入库构建节点 js 项目
- google-apps-script - 例外:无法发送电子邮件:Google 表格中没有收件人(第 38 行,文件“代码”)”错误
- javascript - handleChange 事件侦听器不适用于复选框组件
- swift - 具有 UNNotificationRequest 的计算属性返回无法将类型“Void”的返回表达式转换为返回类型“[UNNotificationRequest]”
- ethereum - 在运行 Geth 命令时,说寻找对等点需要时间)
- ubuntu - 为什么在 ubuntu 18.04 上的 Firefox 上没有加载谷歌字体?
- c# - 向表.net mvc添加新字段后登录表单未提交
- cassandra - 更改 Cassandra UDT 类型以添加多个属性的查询是什么
- json - 如何在scala中更新嵌套的JSON数组
- c# - 包含另一个列表的列表的序列化