0

I have a matrix x_faces with 3 columns and N elements (in this example 4). Per row I want to know if it contains any of the elements from array matches

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

Which should return this:

results = [
        False,
        True,
        True,
        True
    ]

I can think of a for loop that does this, but is there a neat way to do this in python?

bl3nd3d
  • 7
  • 1
  • 2

3 Answers3

2

You could use any() function for that purpose:

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

Output:

[False, True, True, True]
xiº
  • 4,605
  • 3
  • 28
  • 39
  • Is this internally really different from a for-loop? Does list comprehension do some magis to be more effective additionaly to more good-looking? Edit: ah, the thing inside the `any` is a generator expression, right? – Ilja Apr 04 '16 at 16:00
  • I think you should link to [`any`](https://docs.python.org/3.4/library/functions.html#any) in Python3 version instead – Iron Fist Apr 04 '16 at 16:12
  • Thanks, the any() function was what I was looking for – bl3nd3d Apr 05 '16 at 07:27
0

You can use numpy and convert both arrays to 3D and compare them. Then I use sum to determine, whether any of the values in the last two axis is True:

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)
Ilja
  • 2,024
  • 12
  • 28
  • maybe :) depends on the size, doesn't it. I thought, that what you do is in effect a for loop, and he asked for something else :) – Ilja Apr 04 '16 at 16:01
0

I would do something like:

result = [any([n in row for n in matches]) for row in x_faces]
  • [Generator expressions](https://www.python.org/dev/peps/pep-0289/) are best suited in cases like this. Take a look at this [SO](http://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehension) post, and this post [`any()`+generator expression](http://stackoverflow.com/questions/22108103/python-any-generator-expression). Also, in [this](http://stackoverflow.com/a/35837818/3375713) I tried to explain why generator expression is better in cases like this than list comprehensions. – Sнаđошƒаӽ Apr 04 '16 at 17:20