Find index of nested item in python

后端 未结 3 1215
醉话见心
醉话见心 2021-01-22 02:27

I\'ve been working with some relatively complex arrays such as:

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

and I was l

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-22 03:00

    What you want is something like:

    def myindex(lst, target):
        for index, item in enumerate(lst):
            if item == target:
                return [index]
            if isinstance(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:

    def myindex(lst, target):
        for index, item in enumerate(lst):
            if item == target:
                return [index]
            if isinstance(item, str): # or 'basestring' in 2.x
                return []
            try:
                path = myindex(item, target)
            except TypeError:
                pass
            else:
                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.

提交回复
热议问题