加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 23:01:42 所属栏目:Python 来源:网络整理
导读:我想断言两个 Python字典是相等的(这意味着:等量的密钥,每个从键到值的映射是相等的;顺序并不重要).一种简单的方法是断言A == B,但是,如果字典的值是numpy数组,则这不起作用.如果两个词典相同,我怎样才能编写一个函数来检查? import numpy as np A = {1: n
我想断言两个 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读