python – 将两个字典与numpy矩阵作为值进行比较

我想断言两个 Python字典是相等的(这意味着:等量的密钥,每个从键到值的映射是相等的;顺序并不重要).一种简单的方法是断言A == B,但是,如果字典的值是numpy数组,则这不起作用.如果两个词典相同,我怎样才能编写一个函数来检查?
>>> import numpy as np
>>> A = {1: np.identity(5)}
>>> B = {1: np.identity(5) + np.ones([5,5])}
>>> A == B
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

编辑我知道应该检查numpy矩阵与.all()的相等性.我正在寻找的是检查这一点的一般方法,而不必检查isinstance(np.ndarray).这可能吗?

没有numpy数组的相关主题

> Comparing two dictionaries in Python
> Comparing/combining two dictionaries

解决方法

考虑这段代码
>>> import numpy as np
>>> np.identity(5)
array([[ 1.,0.,0.],[ 0.,1.,1.]])
>>> np.identity(5)+np.ones([5,5])
array([[ 2.,1.],[ 1.,2.,2.]])
>>> np.identity(5) == np.identity(5)+np.ones([5,5])
array([[False,False,False],[False,False]],dtype=bool)
>>>

注意,比较的结果是矩阵,而不是布尔值. Dict比较将使用值cmp方法比较值,这意味着在比较矩阵值时,dict比较将得到复合结果.你想要做的就是使用
numpy.all将复合数组结果折叠为标量布尔结果

>>> np.all(np.identity(5) == np.identity(5)+np.ones([5,5]))
False
>>> np.all(np.identity(5) == np.identity(5))
True
>>>

您需要编写自己的函数来比较这些字典,测试值类型以查看它们是否为matricies,然后使用numpy.all进行比较,否则使用==.当然,如果你也想要的话,你可以随时获得幻想并开始子类化dict和重载cmp.

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...