I want to find the index of a particular numpy array with in a sequence. For example, given:
import numpy as np
WHITE = np.array([255, 255, 255])
BLUE = np.array([0, 0, 255])
GRAY = np.array([192, 192, 192])
BLACK = np.array([0, 0, 0])
GREEN = np.array([0, 255, 0])
YELLOW = np.array([255, 255, 0])
COLORS = (WHITE, BLUE, GRAY, BLACK, GREEN)
I'd like to be able to ask for something like
print(COLORS.index(GRAY))
but this leads to the error:
ValueError: The truth value of an array with more than one element
is ambiguous. Use a.any() or a.all()
I do have a workaround, but it feels overly acrobatic:
def index_of(x, sequence):
eq = list((item == x).all() for item in sequence)
return eq.index(True)
print(index_of(GRAY, COLORS))
Is there are more elegant/Pythonic way to do this?
dict? But essentially, no, sinceindexuses==and==produces an array.next(i for (i, item) in enumerate(sequence) if (item == x).all())would be slightly more elegant I think, although it is not very pretty eitherlist(<generator expression>)and just using a list-comprehension. Or better yet, just use a for-loop and return early....