Find index of nested item in python

后端 未结 3 1214
醉话见心
醉话见心 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 02:49

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

    def find_index(array, item, index=None):
        if not index:
            index = []
        try:
            i = array.index(item)
        except:
            for new_array in array:
               if hasattr(new_array, '__iter__'):
                   i = find_index(new_array, item, index+[array.index(new_array)])
                   if i:
                       return i
        else:
            return index + [i]
        return None
    

    This gives:

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

提交回复
热议问题