Welcome, guest | Sign In | My Account | Store | Cart

This module/function lets you find a 2 dimensional list of indices for elements you are looking for in a super list. Example:

find([1,1,1,2,1,2,3,3],[1,2,3])

returns: [[0, 1, 2, 4], [3, 5], [6, 7]]

Python, 9 lines
1
2
3
4
5
6
7
8
9
def find(searchList, elem):
        endList = []
        for indElem in range(0,len(elem)):
            resultList = []
            for ind in range(0, len(searchList)):
                if searchList[ind] == elem[indElem]:
                    resultList.append(ind)
            endList.extend([resultList])
        return endList

You would most likely want to use this module/function when you are trying to find more than one element in a list and do not want to split up the work by using more than one find function. This function can also be used to find only 1 element in a list. This can be done but the number you are searching for must have [] brackets around it. Example: find([1,1,1,2,1,2,3,3],[1])

Returns: [[0, 1, 2, 4]]

4 comments

Andrey Telnov 10 years, 1 month ago  # | flag
def find(searchList, elem):
    return [[i for i, x in enumerate(searchList) if x == e] for e in elem]
Alexander James Wallar (author) 10 years, 1 month ago  # | flag

Wow that is really cool! Thanks

Alexander James Wallar (author) 10 years, 1 month ago  # | flag

How does it work?

Alexander James Wallar (author) 10 years, 1 month ago  # | flag

Oh! I got it.

Thank You very much :D