This algorithm searches for more than one element in a list. The input is a list that you want to search through and a list of elements that you want to search for. The output is a multidimensional list with the positions of the elements you are searching for in the search list in the order that you listed them.
1 | find = lambda searchList, elem: [[i for i, x in enumerate(searchList) if x == e] for e in elem]
|
I would like to acknowledge especially Andrey Telnov for rewriting the loop and introducing me into 1 line for loops and I would like to acknowledge Seung-jin Kim for introducing me to the lambda function and helping to make my primeList algorithm only one line.
Example:
find([1,4,1,4,6,5,5,5,4,2,3],[1,3,5])
Returns: [[0, 2], [10], [5, 6, 7]]
Depending upon your use-case(s), collections.defaultdict (think 'keyed' lists for each set of indexes) can offer some utility for this kind of application. As well, filter or itertools.ifilter can be used. Finally, the comprehension you are using is a staple but is also available as:
At first blush it doesn't seem much different than the square-brackets. Check out the docs for the nuances (as with filter :: ifilter too).
Tradeoff's with the modules I note above are insignificant with small iterations (10k iterations with fractions of seconds difference) but long-term readability, and extra functionality, can be a benefit.
While "slower" than the recipe, here's a starting point to play with if you like:
Hopefully this will help someone along the way.