我无法解决递归嵌套列表的问题。问题;需要定义一个过程来访问任意深度的嵌套列表。它将采用一个嵌套列表和一个索引,并返回该索引处的列表部分。从这个给定的函数中,递归地查找给定索引处的值。
例如
这是一个更好的视觉表示。要从中选择元素 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/