如何获取 n 维嵌套列表的元素的索引

How to get the indexes of an element of a nested list of n dimensions

我是 Python(一般编程)的新手,我遇到了一些不知道如何解决的问题。 我有许多遵循这种模式的不同嵌套列表:

Listi = [string0, string1, ..., stringn, [list0], [list1], ..., [listn]]

(该列表包含一些始终位于开头的字符串,由一些始终位于后面的列表继续)

第一个列表中包含的列表与第一个列表具有完全相同的结构。 列表中可以包含任意数量的列表。

我想编写的是一个函数,给定一个随机元素(一个随机字符串)在列表中找到该元素的索引,以便可以从包含它的主要列表中调用该元素。

我希望获得在操作次数方面实现该目标的最佳方法,但任何解决方案都将不胜感激。

下面是一些例子: 假设我有这两个列表:

l1 = ['Node_50', ['Node_48', 'Node_23'], ['Node_22', ['Node_44'], ['Node_7', 'Node_40']]]
l2 = ['Node_50', ['Node_48', 'Node_23', ['Node_12', 'Node_3'], ['Node_20']], ['Node_22', ['Node_44'], ['Node_7', 'Node_40']]]

我想要一个这样的函数:

def functionfinder(list, element):

这样:

indexes = functionfinder(l1, "Node_40")

indexes 将是一个元组 (2, 2, 1) 因为:

l1[2][2][1] = Node_40

由于您要搜索嵌套列表,因此最好使用递归例程。由于您想要更快的速度,因此例程应该在找到所需项目后立即退出(而不是继续搜索或寻找另一个)。如果您实际上仅使用列表作为字符串的容器,则以下内容应该有效。

def functionfinder(asequence, value, indexes_tuple=()):
    for ndx, item in enumerate(asequence):
        if item == value:  
            return indexes_tuple + (ndx,) # found it here: return the answer
        if isinstance(item, list):
            result = functionfinder(item, value, indexes_tuple + (ndx,))
            if result:  
                return result # found it below: stop looking for it
    return ()  # desired value not found yet

l1 = ['Node_50',
      ['Node_48', 'Node_23'],
      ['Node_22', ['Node_44'], ['Node_7', 'Node_40']]
     ]
l2 = ['Node_50',
      ['Node_48', 'Node_23', ['Node_12', 'Node_3'], ['Node_20']],
      ['Node_22', ['Node_44'], ['Node_7', 'Node_40']]
     ]

indexes = functionfinder(l1, "Node_40")
print(indexes)

该代码的打印输出就是您想要的:

(2, 2, 1)

如果您有 indexes 并且想要访问搜索到的值,您可以执行

result = l1
for ndx in indexes:
    result = result[ndx]

现在 result 包含您搜索的值。

此代码可以推广以处理其他类型的序列,例如元组,而不仅仅是列表。您需要注意不要递归到字符串中,因为 Python 的字符串也是字符序列。你想要一个元组作为 return 值,所以我的代码也使用它们。使用不可变类型作为 return 值确实有优势。但是使用可变类型(例如列表)可能会加快执行速度。就像现在一样,参数中的每个新列表都需要构建一个完整的新索引元组。使用列表可能意味着您只需要附加一个新索引并可能加快代码速度。询问这些可能的改进是否对您有吸引力。

请注意,由于 Python 没有 built-in 立即停止递归函数的方法,因此我的代码使用 returned 空元组来说明所需的项目具有尚未被发现。找到该项目后,将 non-empty 元组结果 returned 表示递归的所有级别尽快停止。这使代码有些复杂。