Problem:
I have a list of lists, e.g [[1,2,3],[1,4,5],[2,7,6,4]], and I want to find the indices corresponding to lists with a given element; If the element I'm interested in is 4, 4 is in both [1,4,5] and [2,7,6,4] so I expect to obtain the indices of these lists in the main list, that is [1,2]. (I'm most interested in a Python solution.)
Attempt: Inspired by Find indices in numpy arrays consisting of lists where element is in list, I intended to use numpy.vectorize as follows:
import numpy
list = [[1,2,3],[1,4,5],[2,7,6,4]]
part_of = numpy.vectorize(lambda: 4 in x)
np.where(part_of(list))
The above works just fine, but when I have a list of lists of the same length, for instance,
list = [[1,2,3],[1,4,5],[2,7,4]]
it seems to break down and I get an error saying that int is not iterable, so that it seems it's iterating on a deeper level than I intended. I can imagine an easy work around to this, if the problem is indeed the broadcasting rules and having lists of different sizes is indeed sufficient for it to work, i.e adding a list of a different size without the desired element, but I wonder if there is a neater way or if I'm missing something simple. On my actual application, there will be many, lists inside the main list, so if there are considerably more efficient solutions, these are very much welcomed as well.
Thank you!
[i for i, item in enumerate(lst) if element in item].np.array(list)for the two cases. Do you see a difference? Inshape,dtype. Before usingnp.vectorizeread its docs carefully, paying attention to what it passes to your function, and its speed disclaimer.numpyonly has a chance of being better ifnp.array(list)already exists, and produces a 2d array.numpyis not magic, improving every problem.