如何比较涉及列表的两个元组的相等性

时间:2019-12-07 01:06:54

标签: python numpy unit-testing

找到了thisthis,但不能解决我的问题。

我想通过比较两个元组作为一个整体而不是逐个元素来执行单元测试。 元组包含int和boolean列表。清单的长度因我的实际情况而异。为简单起见,出于演示目的,我将列表的长度固定为2。 所以我要进行单元测试的功能给出了输出格式,如下所示:

A = some_function(input)
where 
$ some_function(input)
> (array([ True, True]), array([ True, False]), 2)

我试图通过创建B来对A进行单元测试,如下所示:

B = (np.array([True, True]), np.array([True, False]), 2)

我尝试了以下操作,但是都返回False而不是True。为什么?我该如何解决?

np.array_equal(A,B) 
> False 
np.array_equiv(A,B)
> False 
A==B

>ValueError                                Traceback (most recent call last)
<ipython-input-125-2c88eac8e390> in <module>
      1 A=_tokenwise_to_entitywise(ref,hyp)
----> 2 B== (np.array([True,True]), np.array([True,False]), 2)
      3 
      4 A==B

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

2 个答案:

答案 0 :(得分:1)

>>> a
(array([ True,  True]), array([ True, False]), 2)
>>> b
(array([ True,  True]), array([ True, False]), 2)
>>> a==b
Traceback (most recent call last):
  File "<pyshell#75>", line 1, in <module>
    a==b
ValueError: The truth value of an array with more than one element is ambiguous. Use  a.any() or a.all()

相等性测试按元素进行比较。 ndarray比较返回一个ndarray。

>>> a[0]==b[0]
array([ True,  True])
>>> 

错误消息指出这可能是模棱两可的。如果在SO中搜索The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(),则会发现许多常见问题解答

>>> bool(a[0]==b[0])
Traceback (most recent call last):
  File "<pyshell#78>", line 1, in <module>
    bool(a[0]==b[0])
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> 

您的第一个链接几乎将您带到了那里,您只需将np.all应用于每个元素的比较。

>>> all(np.all(x==y) for x,y in zip(a,b))
True
>>> #or
>>> any(map(np.all,zip(a,b)))
True
>>>

我必须考虑一下,看看是否有更好的方法。

答案 1 :(得分:-1)

我无法发表评论,但是上面的答案应该有用。

或者您可以创建一个可重用的函数。

def equality_check(A, B):
    X = True
    if A==B:
        X = True
    else:
        X = False
    return X

然后您可以运行

print(equality_check(A, B))

关于任何变量,列表,数组,元组等

或者您可以将布尔对象创建为

x = equality_check(A, B)
print(x)

这使您可以存储该布尔值以备后用。

希望这会有所帮助。