检查是否数组是阵列的列表元素

检查是否数组是阵列的列表元素

本文介绍了检查是否数组是阵列的列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有13 Python的numpy的数组:

I have 13 python NumPy arrays:

obj_1=np.array([784,785,786,787,788,789,790,791,792])
obj_2=np.array([716,717,718,730,731,732,721,722,724,726,727])
obj_3=np.array([658,659,660,661,662,663,664,665])
obj_4=np.array([581,582,583,589,590,591,595,597,598,599,601,605,606,613,614])
obj_5=np.array([533,534,535,536,537])
obj_6=np.array([464,469,472,474])
obj_7=np.array([406,409,411,412])
obj_8=np.array([345,346,347,349])
obj_9=np.array([277,278,281,282,283,284,288,296])
obj_10=np.array([217,219,220,223,224])
obj_11=np.array([154,155,156,157,158,159,160,161])
obj_12=np.array([91,92,93,94,95,96,97])
obj_13=np.array([28,29,30,31,32,33,34])

然后下面的循环:

Then the following loop:

for i in [obj_1, obj_2, obj_3, obj_4, obj_5, obj_6, obj_7, obj_8, obj_9, obj_10, obj_11, obj_12, obj_13]:
    print i in [obj_1, obj_2, obj_3, obj_4, obj_5, obj_6, obj_7, obj_8, obj_9]

我希望这样的输出:

I would expect this output:

True
True
True
True
True
True
True
True
True
False
False
False
False

相反,我得到一个错误如下:

Instead I get the following with an error:

True
True
True
True
True
True
Traceback (most recent call last):

File "<ipython-input-221-c03c1ef308c6>", line 16, in <module>
print i in [obj_1, obj_2, obj_3, obj_4, obj_5, obj_6, obj_7, obj_8, obj_9]

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

我测试了相同的名称和相同的循环不同的阵列;他们生产的任何错误。

I tested different arrays with the same names and the same for loop; they produced no error.

这似乎是问题出在阵列中的内容,但我想不通的地方。

It seems like the problem lies in the content of the arrays, but I couldn't figure out where.

有没有人有一个想法,为什么出现这种情况?

Does anyone have an idea why this happens?

推荐答案

当你做 OBJ在列表蟒蛇比较 OBJ 与每个列表的成员的平等。问题是,在numpy的平等经营者不以一致的方式行事。例如:

When you do obj in list python compares obj for equality with each of the members of list. The problem is that the equality operator in numpy doesn't behave in a consistent way. For example:

>>> obj_3 == obj_6
False

因为他们有不同的长度,一个布尔返回。

because they have different lengths, a boolean is returned.

>>> obj_7==obj_6
array([False, False, False, False], dtype=bool)

,因为它们具有相同的长度,所述阵列进行比较元件明智并返回numpy的数组。在这种情况下,真值是不确定的。它看起来像这样奇怪的行为是要。

正确的方式做这将是单独每对例如使用的:

The correct way to do it would be to compare individually each pair of arrays using for example numpy.array_equal:

for i in [obj_1, obj_2, obj_3, obj_4, obj_5, obj_6, obj_7, obj_8, obj_9, obj_10, obj_11, obj_12, obj_13]:
    print any(np.array_equal(i, j) for j in [obj_1, obj_2, obj_3, obj_4, obj_5, obj_6, obj_7, obj_8, obj_9])

让你:

True
True
True
True
True
True
True
True
True
False
False
False
False

这篇关于检查是否数组是阵列的列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:51