Skip to content Skip to sidebar Skip to footer

Searching For An Element Inside A Multi-dimensional List And To Return The Sub-list Number?

Previously I had a question on finding whether an element exists in a nested list or not and got the response in the below link. Search of Element inside a multi-dimensional List N

Solution 1:

Since your original function can deal with much more complicated nested structures than just lists of lists, so should your nested 'index' function:

defin_nested_list(item, x):
    if item == x:
        return []
    ifisinstance(x, list):
        for i, ix inenumerate(x):
            r = in_nested_list(item, ix)
            if r != -1:
                return [i] + r  # highest level index plus path in sublistreturn -1# not found in any (nested) sublist# if not found at all: return -1# if item == x: return []# else: return [a, b, c] such that item == x[a][b][c]

> in_nested_list(3, [[1, 2], [3, 4]])
[1, 0]

> in_nested_list(3, [[1, 2], [[5, 3], 4]])
[1, 0, 1]

> in_nested_list(3, 3)
[]

> in_nested_list(3, [1, 2])
# -1

This allows you to append stuff at any nesting level of your choosing. As for your question, the index of the sublist in your simple structure would be in_nested_list(...)[0] (if present, raises Error otherwise).

Solution 2:

I took leverage to modify your function.

defin_nested(item, container):
    ifnotisinstance(container, list):
        raise TypeError
    for elem in container:
        ifisinstance(elem, list):
            found = in_nested(item, elem)
            ifnot found:
                passelifisinstance(found, bool):
                # Item is present in this listreturn elem
                # List containing item is present in this container# Comment above return to use it.return container
            else:
                # Return the deepest list and not the most outer list containing it.return found
        else:
            return item == elem


_input = [[['red'], ['blue'], ['bla']], [['hello'], ['blue'], ['bla']]]
out = in_nested('hello', _input)
if out:
    print"Found Hello", out
else:
    print"Not Found Hello"

out.append('new')
print'Added new to original input', _input

out = in_nested('Hello', _input)  # hello with capital Hif out:
    print"Found Hello", out
else:
    print"Not Found Hello"# Prints:# Found Hello ['hello']# Added new to original input [[['red'], ['blue'], ['bla']], [['hello', 'new'], ['blue'], ['bla']]]# Not Found Hello

Note: It gives you the target list itself, if item is present else None. You don't have to locate the list again. Just append to the result.

Post a Comment for "Searching For An Element Inside A Multi-dimensional List And To Return The Sub-list Number?"