python - 递归嵌套列表

标签 python list recursion nested

我无法解决递归嵌套列表的问题。问题;需要定义一个过程来访问任意深度的嵌套列表。它将采用一个嵌套列表和一个索引,并返回该索引处的列表部分。从这个给定的函数中,递归地查找给定索引处的值。

例如

这是一个更好的视觉表示。要从中选择元素 9,我们需要执行类似的操作 嵌套[3][1]

    nested = \
    [[[1, 2],
      3],
     [4,
      [5, 6]],
     7,
     [8, 9, 10]]

recursive_func(nested_list, [3,1]) #recursive function definition, the second argument is the index at which the data needs to be retrieved.  
>>> 9 #so given the function an index of [3,1] would return 9

任何帮助我指明正确方向的帮助将不胜感激

最佳答案

这可能对你有用,但我仍然不能 100% 确定你在寻找什么......

>>> def findItem(nested, pos):
    if pos[0] == 1:
        return nested[pos[1]-1]
    else:
        nextLevelDown = []
        for item in nested:
            if type(item) == type([]):
                nextLevelDown = nextLevelDown + item
        return findItem(nextLevelDown, [pos[0]-1, pos[1]])

>>> findItem([[[1, 2], 3], 4], [3, 1])
1
>>> findItem([[[1, 2], [3]], 4], [3, 3])
3
>>> findItem([[[1, 2], [3]], 4], [2, 2])
[3]

更新:经过多次来回,我终于明白了这个问题,而且它比最初看起来简单得多,你所需要的是:

>>> def recursiveRef(nested, idxList):
    if len(idxList) > 1:
        return recursiveRef(nested[idxList[0]], idxList[1:])
    return nested[idxList[0]] 

>>> recursiveRef([[[1, 2], 3], [4, [5, 6]], 7, [8, 9, 10]], [3, 1])
9

关于python - 递归嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5946648/

相关文章:

javascript - 如何向 Chrome 扩展程序发送数据?

python - 在 python sqlite3 模块中导入数据文件(如.csv)的任何其他方式? [不一一插入]

python - 如何将 numpy 1D 数组插入 numpy 3D 数组?

java - Parcelable 对象列表的包裹列表

list - <li> 元素上的 CSS3 box-shadow 不起作用

java - 递归检查数组是否包含 0 (java)

用于手 Action 业提交 Maya 到截止日期的 Python 命令(包括提交 maya 场景文件)

python - 按值对枚举列表进行排序

JavaScript:带有 Promise 的递归函数,解析返回 "undefined"

c++ - 具有常量参数的递归函数