检查numpy数组是否在numpy数组列表中 [英] Check if numpy array is in list of numpy arrays

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

问题描述

我有一个numpy数组和一个numpy数组的列表.我想检查单个数组是否是列表的成员.

I have a list of numpy arrays and a single numpy array. I want to check if that single array is a member of the list.

我想有一个方法,我没有正确搜索...这就是我想出的:

I suppose there exist a method and I haven't searched properly... This is what I came up with:

def inList(array, list):
    for element in list:
        if np.array_equal(element, array):
            return True
    return False

此实现正确吗?有任何准备好的功能吗?

Is this implementation correct? Is there any ready function for this?

推荐答案

在谈论python时使用动词is有点含糊.这个例子涵盖了我可能想到的所有情况:

Using the verb is when talking about python is a bit ambiguous. This example covers all the cases I could think of:

from __future__ import print_function
from numpy import array, array_equal, allclose

myarr0 = array([1, 0])
myarr1 = array([3.4499999, 3.2])
mylistarr = [array([1, 2, 3]), array([1, 0]), array([3.45, 3.2])]

#test for identity:
def is_arr_in_list(myarr, list_arrays):
    return next((True for elem in list_arrays if elem is myarr), False)

print(is_arr_in_list(mylistarr[2], mylistarr)) #->True
print(is_arr_in_list(myarr0, mylistarr)) #->False
#myarr0 is equal to mylistarr[1], but it is not the same object!

#test for exact equality
def arreq_in_list(myarr, list_arrays):
    return next((True for elem in list_arrays if array_equal(elem, myarr)), False)

print(arreq_in_list(myarr0, mylistarr)) # -> True
print(arreq_in_list(myarr1, mylistarr)) # -> False

#test for approximate equality (for floating point types)
def arreqclose_in_list(myarr, list_arrays):
    return next((True for elem in list_arrays if elem.size == myarr.size and allclose(elem, myarr)), False)

print(arreqclose_in_list(myarr1, mylistarr)) #-> True

PS:请勿将list用作变量名,因为它是保留关键字,通常会导致细微的错误.同样,请勿使用array.

PS:do NOT use list for a variable name, as it is a reserved keyword, and often leads to subtle errors. Similarly, do not use array.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆