查找蟒蛇嵌套项目的索引 [英] Find index of nested item in python

查看:118
本文介绍了查找蟒蛇嵌套项目的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直与一些相对复杂的阵列,如:

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

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

和我一直在寻找一种方式来找到一个项目和检索是指数(是否确定要参考项目的位置,如A - 这是一个元组里面作为同一水平数组索引?)

and I was looking for a way to find an item and retrieve is "index" (Is it OK to refer to the location of item such as "a" - that is inside a Tuple as index on the same level as array?)

现在我首先想到的是使用像一个简单的辅助功能,例如:

Now my first thought was to use something like a simple helper function such as:

def myindex(nestedlist, item):
    for i in nestedlist:
        if item in i:
         index = []
         index.append(i)
         index.append(i.index(item))
         return index

但我敢肯定你能猜到,这样的功能不会做多好,尤其是因为我不知道提前做数组可能多少级都有,什么每个级别可能包含(在数据方面类型/结构)

But I'm sure you can guess that such a function won't do much good, especially since I don't know in advance how many levels the array might have, and what each level might contain (in terms of data type/structure)

在正确的方向任何暗示将是非常美联社preciate!

Any hint in the right direction would be highly appreciate!

推荐答案

你想要的是一样的东西:

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]


正如亚当暗示的意见,明确检查的实例类型不是很Python的。一个鸭类型的,的更容易请求原谅比许可替代方案是:

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.

这篇关于查找蟒蛇嵌套项目的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆