jfaccioni
jfaccioni

Reputation: 7529

How to check if a numpy array is inside a Python sequence?

I'd like to check if a given array is inside a regular Python sequence (list, tuple, etc). For example, consider the following code:

import numpy as np

xs = np.array([1, 2, 3])
ys = np.array([4, 5, 6])

myseq = (xs, 1, True, ys, 'hello')

I would expect that simple membership checking with in would work, e.g.:

>>> xs in myseq
True

But apparently it fails if the element I'm trying to find isn't at the first position of myseq, e.g.:

>>> ys in myseq
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

So how can I perform this check?

If possible I'd like to do this without having to cast myseq into a numpy array or any other sort of data structure.

Upvotes: 0

Views: 617

Answers (2)

dawg
dawg

Reputation: 104024

You can use any with the test that is appropriate:

import numpy as np

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

myseq = (xs, 1, True, ys, 'hello')

def arr_in_seq(arr, seq):
    tp=type(arr)
    return any(isinstance(e, tp) and np.array_equiv(e, arr) for e in seq)

Testing:

for x in (xs,ys,zs):
    print(arr_in_seq(x,myseq))
True
True
False

Upvotes: 1

mapf
mapf

Reputation: 2068

This is probably not the most beatiful or fasted solution, but I think it works:

import numpy as np


def array_in_tuple(array, tpl):
    i = 0
    while i < len(tpl):
        if isinstance(tpl[i], np.ndarray) and np.array_equal(array, tpl[i]):
            return True
        i += 1
    return False


xs = np.array([1, 2, 3])
ys = np.array([4, 5, 6])

myseq = (xs, 1, True, ys, 'hello')


print(array_in_tuple(xs, myseq), array_in_tuple(ys, myseq), array_in_tuple(np.array([7, 8, 9]), myseq))

Upvotes: 1

Related Questions