Skip to content Skip to sidebar Skip to footer

Find Index Of Nested Item In Python

I've been working with some relatively complex arrays such as: array = [ '1', 2, ['4', '5', ('a', 'b')], ('c', 'd')] and I was looking for a way to find an item and retrieve is 'i

Solution 1:

What you want is something like:

defmyindex(lst, target):
    for index, item inenumerate(lst):
        if item == target:
            return [index]
        ifisinstance(item, (list, tuple)):
            path = myindex(item, target)
            if path:
                return [index] + path
    return []

Being recursive, this will deal with arbitrary depth of nesting (up to the recursion limit).

For your example array, I get:

>>>myindex(array, "a")
[2, 2, 0]

As Adam alludes to in the comments, explicitly checking instance types isn't very Pythonic. A duck-typed, "easier to ask for forgiveness than permission" alternative would be:

defmyindex(lst, target):
    for index, item inenumerate(lst):
        if item == target:
            return [index]
        ifisinstance(item, str): # or 'basestring' in 2.xreturn []
        try:
            path = myindex(item, target)
        except TypeError:
            passelse:
            if path:
                return [index] + path
    return []

The specific handling of strings is necessary as even an empty string can be iterated over, causing endless recursion.

Solution 2:

array = [ "1", 2, ["4", "5", ("a", "b")], ("c", "d")]

deffind_index(array, item, index=None):
    ifnot index:
        index = []
    try:
        i = array.index(item)
    except:
        for new_array in array:
           ifhasattr(new_array, '__iter__'):
               i = find_index(new_array, item, index+[array.index(new_array)])
               if i:
                   return i
    else:
        return index + [i]
    returnNone

This gives:

>>> find_index(array, 1)
>>> find_index(array, "1")
[0]
>>> find_index(array, 2)
[1]
>>> find_index(array, "4")
[2, 0]

Solution 3:

I'm a bit late to the party, but I spent several minutes on it so I feel like it ought to be posted anyway :)

defgetindex(container, target, chain=None):
    if chain isNone: chain = list()
    for idx, item inenumerate(container):
        if item == target:
            return chain + [idx]
        ifisinstance(item, collections.Iterable) andnotisinstance(item, str):
            # this should be ... not isinstance(item, basestring) in python2.x
            result = getindex(item, target, chain + [idx])
            if result:
                return result
    returnNone

Post a Comment for "Find Index Of Nested Item In Python"