5

This is the list of matrices;

[matrix([[1, 0],
         [1, 0],
         [1, 0],
         [1, 0]]),
 matrix([[0, 0, 0, 0],
         [1, 1, 1, 1]]),
 matrix([[0, 1],
         [0, 1],
         [0, 1],
         [0, 1]]),
 matrix([[0, 0, 0, 0],
         [1, 1, 1, 1]]),
 matrix([[1, 1, 1, 1],
         [0, 0, 0, 0]])]

and I want to check if a matrix is already inside the list example;

a = matrix([[0, 0, 0, 1],
            [1, 1, 1, 0]])

So if a is in m then print True else print False

LightninBolt74
  • 211
  • 4
  • 11
epaikins
  • 69
  • 1
  • 5

1 Answers1

4

I assume you are using NumPy. If this is the case, don't use np.matrix, use np.array. np.matrix exists almost exclusively for legacy reasons and has undesirable features.

You can use any with a generator comprehension and np.array_equal. This will short-circuit to True if the array is found in the input list, otherwise return False.

import numpy as np

L = [np.array([[1, 0], [1, 0], [1, 0], [1, 0]]),
     np.array([[0, 0, 0, 0], [1, 1, 1, 1]]),
     np.array([[0, 1], [0, 1], [0, 1], [0, 1]]),
     np.array([[0, 0, 0, 0], [1, 1, 1, 1]]),
     np.array([[1, 1, 1, 1], [0, 0, 0, 0]])]

A = np.array([[0, 0, 0, 1], [1, 1, 1, 0]])

res = any(np.array_equal(A, i) for i in L)  # False
jpp
  • 159,742
  • 34
  • 281
  • 339
  • thanks but I am getting this " at 0x7fe874754aa0>" – epaikins Oct 03 '18 at 23:56
  • Figured it out, the last line of code should be "res = any([np.array_equal(A, i) for i in L])" – epaikins Oct 04 '18 at 00:00
  • 1
    No, `res = any(np.array_equal(A, i) for i in L)` should work fine. Using a list comprehension isn't recommended as it requires building a `list` first, which isn't necessary for this task. – jpp Oct 04 '18 at 00:00
  • The bad `any` output observed by the questioner is a symptom of using `from numpy import *`, or something else that hides the built-in `any` with `numpy.any`. This is one of the primary examples of why not to use star imports. – user2357112 Apr 19 '20 at 09:31