递归嵌套列表
我在理解一个关于递归嵌套列表的问题时遇到了困难。这个问题是:需要定义一个过程来访问一个嵌套列表,深度可以是任意的。这个过程会接收一个嵌套列表和一个索引,然后返回该索引位置的部分内容。接着,利用这个函数递归地找到给定索引的值。
举个例子
这里有一个更好的可视化表示。要从中选择元素9,我们需要这样做:nested[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
如果能给我一些指引,我将非常感激。
2 个回答
0
如果我理解得没错的话,你想把嵌套的列表变成不嵌套的列表?然后再检查索引?如果是这样的话,你可以试试下面这个方法(我现在没有python,所以这就当作伪代码来看):
def unwrap_list(list, result):
if type(list) == type([]):
for value in list:
unwrap_list(value, result)
else:
result.append(list)
在调用这个函数之前,确保先定义一个变量 unwrapped = []
,然后使用 unwrap_list(list, unwrapped)
。结果会存储在变量 unwrapped
中。
1
这可能对你有帮助,但我还是不太确定你到底在找什么...
>>> 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