繁体   English   中英

检查数组的数组元素是否存在于 python 中的另一个数组中

[英]Check whether array elements of array are present in another array in python

我有两个 arrays 为:

a = [[1,2,3,4],[3,1,2,4],[4,3,1,2],...]b = [[4,1,2,3],[1,2,3,4],[3,2,4,1]....]

如果在b中找到a的每个行元素,我想返回一个True 对于上述示例的可见部分,结果应为 c = [True, False, False]。 欢迎使用 Numpy 解决方案。

最幼稚的解决方案:

[(x in b) for x in a]
#[True, False, False]

一个更有效的解决方案(对于大型列表工作得更快,因为集合具有恒定的查找时间,但列表具有线性查找时间):

set_b = set(map(tuple, b)) # Convert b into a set of tuples
[(x in set_b) for x in map(tuple,a)]
#[True, False, False]

您可以为此使用numpy

import numpy as np
a = np.array([[1,2,3,4],[3,1,2,4],[4,3,1,2]])
b = np.array([[4,1,2,3],[1,2,3,4],[3,2,4,1]])    
(a[:, None] == b).all(-1).any(-1)

out: array([ True, False, False])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM