2016-04-04 39 views
0

我有一个矩阵x_faces有3列和N个元素(在本例中为4)。 每行,我想知道它是否包含任何元素的数组matches与矩阵行中的元素匹配数组

x_faces = [[ 0, 43, 446], 
      [ 8, 43, 446], 
      [ 0, 10, 446], 
      [ 0, 5, 425] 
      ] 
matches = [8, 10, 44, 425, 440] 

应返回此:

results = [ 
     False, 
     True, 
     True, 
     True 
    ] 

我能想到的一个for循环,这样做,但有一个干净的方式来做到这一点在Python中?

+0

我找到了更快的方法:'np.any( np.in1d(x_faces,匹配[i])。reshape(-1,3),axis = 1)' – bl3nd3d

回答

2

你可以使用​​功能用于这一目的:

result = [any(x in items for x in matches) for items in x_faces] 

输出:

[False, True, True, True] 
+0

这是否与for循环内部真的不同?列表理解是否会使某些魔力更加有效地增加更好看? 编辑:啊,'any'里面的东西是一个生成器表达式,对吧? – Ilja

+0

我想你应该在Python3版本中链接到['any'](https://docs.python.org/3.4/library/functions.html#any)而不是 –

+0

谢谢,any()函数就是我正在寻找的东西对于 – bl3nd3d

0

您可以使用numpy的和两个数组转换为3D并加以比较。然后我用总和来确定,任何在最后两轴的值是否为真:

x_faces = np.array([[ 0, 43, 446], 
      [ 8, 43, 446], 
      [ 0, 10, 446], 
      [ 0, 5, 425] 
      ]) 
matches = np.array([8, 10, 44, 425, 440]) 
shape1, shape2 = x_faces.shape, matches.shape 
x_faces = x_faces.reshape((shape1 + (1,))) 
mathes = matches.reshape((1, 1) + shape2) 
equals = (x_faces == matches) 
print np.sum(np.sum(equals, axis=-1), axis=-1, dtype=bool) 
+0

是不是这个任务的开销。 –

+0

也许:)取决于大小,不是。我想,你所做的实际上是一个for循环,并且他要求别的东西:) – Ilja

0

我会做这样的事情:

result = [any([n in row for n in matches]) for row in x_faces] 
+0

[Generator expressions](https://www.python.org/dev/peps/pep-0289/)是最合适的在这种情况下。看看这个[SO](http://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehension)后,这篇文章['任何()'+生成器表达式](http:///stackoverflow.com/questions/22108103/python-any-generator-expression)。另外,在[this](http://stackoverflow.com/a/35837818/3375713)中,我尝试解释为什么生成器表达式在这种情况下比列表解析更好。 –