Find index of nested item in python

后端 未结 3 1252
醉话见心
醉话见心 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:01

    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 :)

    def getindex(container, target, chain=None):
        if chain is None: chain = list()
        for idx, item in enumerate(container):
            if item == target:
                return chain + [idx]
            if isinstance(item, collections.Iterable) and not isinstance(item, str):
                # this should be ... not isinstance(item, basestring) in python2.x
                result = getindex(item, target, chain + [idx])
                if result:
                    return result
        return None
    

提交回复
热议问题