How to search a list of arrays

Consider the following list of two arrays:

from numpy import array

a = array([0, 1])
b = array([1, 0])

l = [a,b]

Then index search acorrectly gives

l.index(a)
>>> 0

until it works for b:

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

It seems to me that calling a list .indexdoes not work for numpy array lists.

Does anyone know an explanation? Until now, I have always solved this problem, as if it were turning arrays into strings. Does anyone know a more elegant and faster solution?

+4
source share
2 answers

, l.index[a] . numpy : l[1] == b , , . array([ True, True], dtype=bool), , , .

, Python , , PyObject_RichCompareBool, , , , (a is b) (a == b). , , a is l[0], 0.

, . ( Ashwini Chaudhary ).

, , , l[0]:

d = array([0,1])
l.index(d)

, , .

, - , (index, in, remove) , , @orestiss. , numpy , :

>>> class NArray(object):
    def __init__(self, arr):
        self.arr = arr
    def array(self):
        return self.arr
    def __eq__(self, other):
        if (other.arr is self.arr):
            return True
        return (self.arr == other.arr).all()
    def __ne__(self, other):
        return not (self == other)


>>> a = array([0, 1])
>>> b = array([1, 0])
>>> l = [ NArray(a), NArray(b) ]
>>> l.index(NArray(a))
0
>>> l.index(NArray(b))
1
+1

, numpy : ,

, , , , .

, - :

[i for i, temp in enumerate(l) if (temp == b).all()]

, python, (, ...)

0

Source: https://habr.com/ru/post/1617203/


All Articles