I have a list of lists similar to this:
L = {{"a", "b", "c"}, {"x", "c", "y"}, {"i", "j", "h"}, {"x", "b", "z"}}
Each list within L
happens to be of length 3. Suppose I need to find the position of the lists that have a particular element (say, "b") at the $n^{th}$ position. How can I do this efficiently?
Currently, I have an approach that works but I don't think it is very efficient inefficient (it creates a new list with the $n^{th}$ elements and then looks for the queried element, I'm sure there's a way to search L
directly):
queriedElement = "b";
queriedPosition = 2;
occurencePositions = Flatten@Position[#[[queriedPosition]] & /@ L, queriedElement]//AbsoluteTiming
Which gives the correct answer:
{0.000035, {1, 4}}
Searching for an alternative efficient way because I need to do this in large lists.
Thanks!
Position[L[[All,2]], "b"]
is probably close to the 'canonical' solution, and it might be of interest that if you don't Flatten, the result may be used directly withExtract
to obtain the full sublists, if desired:Extract[L,%]
$\endgroup$