递归嵌套列表
我无法解决递归嵌套列表上的问题。问题;需要定义一个过程来访问任意深度的嵌套列表。它将采用一个嵌套列表和一个索引,并返回该索引处的列表部分。从这个给定的函数中,递归地找到给定索引处的值。
例如
,这是一个更好的视觉表示。要从中选择元素 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
任何帮助我指明正确方向的帮助将不胜感激
I'm having trouble getting my head around a problem on recursive nested lists. The problem; need to define a procedure to access a nested list to an arbitrary depth. It would take an nested list and an index, and return the part of the list at that index. From this given function, recursively find the value at the given index.
For example
Well here is a better visual representation. To select the element 9 out of it, we need to do something like
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
Any help to point me in the right direction would be grateful
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可能对你有用,但我仍然不是 100% 确定你在寻找什么......
更新:所以经过多次来回,我终于明白了这个问题,它比最初看起来要简单得多,你需要的一切是:
This may do you, but I'm still not 100% sure what you are looking for...
UPDATE: So after much back and forth, I finally understand the question, and it is much simpler than it originally seemed, all you need is:
如果我理解正确的话,您只想将嵌套列表变成非嵌套列表吗?然后检查索引?如果是这样,那么你可以尝试这样的事情(我目前没有 python,所以将其视为伪代码):
确保在调用此函数之前定义变量
unwrapped = []
并使用unwrap_list(list, unwrapped)
。结果将存储在变量unwrapped
中。If I understand this correctly, you want simply turn nested list into non-nested? And then check the index? If so, then you can try something like this (I don't have python at the moment, so treat it like a pseudocode):
Make sure, to define variable
unwrapped = []
before calling this function and useunwrap_list(list, unwrapped)
. The result will be stored in variableunwrapped
.