python - 在 Python 中,如何返回任意嵌套元素的索引列表?

标签 python recursion functional-programming

假设我有一个列表:

>>> nested=[[1, 2], [3, [4]]]

如果我正在寻找 4,我正在尝试获取一个返回 [1,1,0] 的函数。如果指定的元素不在列表中,那么它将返回一个空列表,[]

Nested 可以有任何结构,所以我认为某种类型的递归函数最好,但我无法控制结构的深度和广度。

这不是工作代码,但符合我的想法:

def locate(x,element,loc=[0],counter=0):
    for c,i in enumerate(x):
        if isinstance(i,list):
            locate(i,loc+[0],counter+1)
        else:
            loc[counter]=c
            if i==element: return loc

函数调用看起来像这样:

>>> locate(nested,4)
[1,1,0]

递归函数可能不是最好的解决方案,但只是我的尝试。

最佳答案

您可能会考虑改用某种树数据结构,但这是您当前数据结构的示例:

from collections import Iterable

def flatten(collection, depth=()):
    for i, element in enumerate(collection):
        if isinstance(element, Iterable) and not isinstance(element, str):
            yield from flatten(element, depth=depth + (i,))
        else:
            yield element, depth + (i,)

def locate(nested, element):
    for v, indices in flatten(nested):
        if v == element:
            return indices

关于python - 在 Python 中,如何返回任意嵌套元素的索引列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40164116/

相关文章:

list - F# 匹配模式鉴别器未定义问题

java - 二叉搜索树递归添加

c++ - 为什么我可以在 C++ 中的函数中定义结构和类?

java - 添加两个 Optional<BigDecimal> 数字的最优雅方法是什么

Scala 递归 API 调用以获取所有结果

python - 我希望包含 y.png 文件的 x 文件夹名称为 z.png

python - 如何根据url请求更改django listview中的模板名称?

r - 处理 R 中的递归深度限制

python - 守护进程 python 包装器 "subprocess I/O timed out",需要一些指导

python - 从随机样本(python)构建一个近似均匀的网格