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

前端 未结 3 1836
-上瘾入骨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

    This solution could work for this case:

    def arrayisin(array, list_of_arrays):
        for a in list_of_arrays:
            if np.array_equal(array, a):
                return True
        return False
    

    This function iterates over a list of arrays and tests the equality against some other array. So the usage would be:

    >>> arrayisin(c, CNTS)
    True
    

    To remove the array from the list, you can get the index of the array and then use list.pop. In the function get_index, we enumerate the list of arrays, meaning we zip the indices of the list and the contents of the list. If there is a match, we return the index of the match.

    def get_index(array, list_of_arrays):
        for j, a in enumerate(list_of_arrays):
            if np.array_equal(array, a):
                return j
        return None
    
    idx = get_index(c, CNTS)  # 1
    CNTS.pop(idx)
    

    Please see the python data structures tutorial for the documentation of list.pop https://docs.python.org/3/tutorial/datastructures.html

提交回复
热议问题