如何为任意列表构建递归? [英] How to build a recursion for arbitrary lists?
问题描述
为了简化我的问题,我将尝试举一个简单的例子来使其更清楚,例如,如果我有这个由列表列表组成的树,列表的数量可以无限大,例如
To simplify my question I will try give a simple example to make it clearer,if I have this Tree made of lists of lists for instance, the number of lists can be infinitely large e.g.
[[[[], []], [[], []]], [[], [], []]]
我想剪掉它的叶子,没有外向边的节点(空列表),所以用前面的输入我得到这个:
And I want to cut off its leaves, the nodes that do not have outgoing edges(empty list), so with the previous input I get this :
[[[], []], []]
如何将递归应用于此类情况?
How can I apply the recursion to this type of situations ?
推荐答案
这应该可以:
prune = lambda tree : [prune(branch) for branch in tree if branch != []]
l = [[[[], []], [[], []]], [[], [], []]]
prune(l)
避免使用 lambda
(改进评论后的风格,另见 如何将这个 lambda 函数转换为 def 格式?) 函数可以定义为:
Avoiding the use of lambda
(improving style following comments, and see also How do I transform this lambda function into def format?) the function can be defined as:
def prune(tree):
return [prune(branch) for branch in tree if branch != []]
这篇关于如何为任意列表构建递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!