Test if a numpy array is a member of a list of numpy arrays, and remove it from the list

前端 未结 3 1871
-上瘾入骨i
-上瘾入骨i 2021-01-18 16:01

When testing if a numpy array c is member of a list of numpy arrays CNTS:

import numpy as np

c = np.array([[[ 75, 763]],
                  


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-18 16:40

    You are getting the error because in essentially invokes bool(c == x) on every element x of CNTS. It's the __bool__ conversion that is raising the error:

    >>> c == CNTS[1]
    array([[[ True,  True]],
           [[ True,  True]],
           [[ True,  True]],
           [[ True,  True]]])
    
    >>> bool(_)
    ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
    

    The same applies for removal, since it tests for equality with each element.

    Containment

    The solution is to use np.array_equal or apply the all method to each comparison:

    any(np.array_equal(c, x) for x in CNTS)
    

    OR

    any((c == x).all() for x in CNTS)
    

    Removal

    To perform the removal, you are more interested in the index of the element than its existence. The fastest way I can think of is to iterate over the indices, using the elements of CNTS as comparison keys:

    index = next((i for i, x in enumerate(CNTS) if (c == x).all()), -1)
    

    This option short circuits quite nicely, and returns -1 as the default index rather than raising a StopIteration. You can remove the argument -1 to next if you prefer the error. If you prefer, you can replace (c == x).all() with np.array_equal(c, x).

    Now you can remove as usual:

    del CNTS[index]
    

提交回复
热议问题