Jsevillamol
Jsevillamol

Reputation: 2543

Create a set of numpy arrays

I want to create a set of numpy arrays and then efficiently perform the in operation.

explored = {
       np.array([[4,9,6,1,2,5], [5,8,3,7,7,9], [2,4,1,6,3,8]]),
       np.array([[1,2,3,1,2,5], [1,2,3,7,7,9], [1,2,3,6,3,8]]),
           }

if array in explored: # where array is an np.array 
    print("the array is already in the set")
else:
    explored.append(array)

But the interpreter complains that np.array is not a hashable type. What can I do instead?

Upvotes: 3

Views: 6280

Answers (1)

Rory Daulton
Rory Daulton

Reputation: 22544

First get a regular np.array:

explored = np.array([[4,9,6,1,2,5], [5,8,3,7,7,9], [2,4,1,6,3,8]])

Then explored is

np.array([[4,9,6,1,2,5], [5,8,3,7,7,9], [2,4,1,6,3,8]])

Then convert that to a set. But to do that, convert each row in the np.array to a tuple, so it is hashable.

explored_set = {tuple(row) for row in explored}

Now explored_set is

{(2, 4, 1, 6, 3, 8), (4, 9, 6, 1, 2, 5), (5, 8, 3, 7, 7, 9)}

Now you can use that for searches:

if tuple(array) in explored_set:
    # processing here

And so on. Note that the order of the set differs from the order of the np.array, as is typical.

Upvotes: 9

Related Questions