Python - 嵌套列表的迭代
从昨天开始我就陷入了一个小而棘手的问题。
我拥有的是一个(可能是无限的)嵌套列表,如下所示:
[1,[2,[3,4]]]
or [[1,2],[3,4]] and so on.
在每个级别上,列表由两个子列表组成,(我没有使用元组,因为列表在下一步中可能会获得任意长度) 现在我想在此列表中的每个可能位置插入一个元素,并返回所有可能插入位置的列表列表。 因此,如果我插入 5,我的输出应该如下所示:
[ [5,[1,[2,[3,4]]]],
[1,[5,[2,[3,4]]]],
[1,[2,[5,[3,4]]]],
[1,[2,[[3,5],4]]],
[1,[2,[3,[4,5]]]] ]
背景:我试图通过一次添加一个分类单元来构建一棵系统发育树。每个分类单元都必须插入到最适合的位置。
我现在得到的是:
def get_trees(nwklist,newid):
if not isinstance(nwklist,list):
return [newid,nwklist]
else:
return [newid,nwklist],[get_trees(nwklist[0],newid),nwklist[1]],[nwklist[0],get_trees(nwklist[1],newid)]
它不会产生我想要的输出,但有点接近。
([5, [1, [2, [3, 4]]]],
[[5, 1], [2, [3, 4]]],
[1, ([5, [2, [3, 4]]], [[5, 2], [3, 4]], [2, ([5, [3, 4]], [[5, 3], 4], [3, [5, 4]])])])
应该有一个简单的解决方案,也许涉及 lambda 函数,但我只是没有看到它。
克里斯托夫
I'm stuck on a small but tricky problem since yesterday.
What I have is a (possibly infinitely) nested list like this:
[1,[2,[3,4]]]
or [[1,2],[3,4]] and so on.
On each level the lists consist of two sublists, (I didn't use tuples because the lists will probably get arbitrary length in the next step)
Now I want to insert an element in every possible position in this list and return an list of lists of all possible insertion positions.
So if I insert 5, my output should look like:
[ [5,[1,[2,[3,4]]]],
[1,[5,[2,[3,4]]]],
[1,[2,[5,[3,4]]]],
[1,[2,[[3,5],4]]],
[1,[2,[3,[4,5]]]] ]
The background: I'm trying to construct an phylogenetic tree by adding one taxon at a time. Each taxon has to be inserted at the position where it fits best.
What I got now is:
def get_trees(nwklist,newid):
if not isinstance(nwklist,list):
return [newid,nwklist]
else:
return [newid,nwklist],[get_trees(nwklist[0],newid),nwklist[1]],[nwklist[0],get_trees(nwklist[1],newid)]
which does not produce the output I want, but comes somewhat close.
([5, [1, [2, [3, 4]]]],
[[5, 1], [2, [3, 4]]],
[1, ([5, [2, [3, 4]]], [[5, 2], [3, 4]], [2, ([5, [3, 4]], [[5, 3], 4], [3, [5, 4]])])])
There should be an easy solution, perhaps involving lambda functions, but I just don't see it.
Christoph
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会使用生成器:
请注意,这会返回比示例中列出的更多的树:
据我所知,这符合规定的要求。如果有一些我不太明白的未说明的要求(例如,如果每个子列表的第一个元素必须是标量),请澄清,我将更新解决方案。
I'd use a generator:
Please note that this returns more trees than listed in your example:
As far as I can see, this ahderes to the stated requirements. If there are some unstated requirements that I didn't quite get (e.g. if the first element of every sublist has to be a scalar), please clarify and I'll update the solution.