微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

原文地址:https://www.jb51.cc/python/241830.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐