[英]Recursive Nested Lists
我无法解决递归嵌套列表中的问题。 问题; 需要定义一个过程来访问嵌套列表到任意深度。 它需要一个嵌套列表和一个索引,然后在该索引处返回列表的一部分。 从这个给定的函数中,递归地找到给定索引处的值。
例如
好吧,这是一个更好的视觉表示。 要从中选择元素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
为我指明正确方向的任何帮助将不胜感激
这可能会帮到您,但是我仍然不是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,因此将其视为伪代码):
def unwrap_list(list, result):
if type(list) == type([]):
for value in list:
unwrap_list(value, result)
else:
result.append(list)
确保在调用此函数之前定义变量unwrap_list(list, unwrapped)
unwrapped = []
,并使用unwrap_list(list, unwrapped)
。 结果将存储在unwrapped
变量中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.