【问题标题】:In Python, how do you return a list of indexes for an arbitarily nested element?在 Python 中,如何返回任意嵌套元素的索引列表?
【发布时间】:2017-03-03 00:36:39
【问题描述】:

假设我有一个清单:

>>> 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]

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

【问题讨论】:

  • 您当前的解决方案有什么问题?除了递归时不返回。并使用默认的可变参数。
  • return locate(i,loc+[0],counter+1)
  • 如果有多个匹配项怎么办?
  • @AndrasDeak 返回第一个实例可以很好地保持类似于列表索引方法的功能

标签: python recursion functional-programming


【解决方案1】:
def nested_find(l, e):
    for i, x in enumerate(l):
        if isinstance(x, list):
            t = nested_find(x, e)
            if t:
                return [i] + t
        elif x == e:
            return [i]

如果e 不在l 中,则返回None

【讨论】:

  • 仅供参考,(x, list); 有一个分号
  • 您介意提供更多关于其工作原理的解释吗?
  • @LMc 当然。这会遍历列表的每个元素,如果该元素本身是一个列表,则在该列表中调用它自己。如果元素等于我们正在寻找的元素,我们返回一个列表,其中包含它在最直接列表中的索引。然后,当我们退出递归调用时,我们添加列表的索引,该索引在某种程度上包含我们正在寻找的内容。如果在列表中没有找到目标元素,它会在没有返回语句的情况下到达末尾,从而返回None
【解决方案2】:

如果未找到元素,则以下代码返回 None,否则返回所需的输出:

   def locate(lst,ele):
        return  _locate(lst,ele,[])

    def _locate(lst,ele,res):
        for i,x in enumerate(lst):
            if isinstance(x,list):
                retVal = locate(x,ele,res+[i])
                if retVal is not None:
                    return retVal
            elif x==ele:
                return res+[i]
        return None

【讨论】:

    【解决方案3】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-16
      • 1970-01-01
      • 2012-10-10
      • 2016-02-29
      • 2022-10-05
      相关资源
      最近更新 更多