且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用递归从列表中删除某些内容?Python

更新时间:2023-11-29 07:51:09

解决方案:

def tree_cut(tree):返回 [tree_cut(x) for x in tree if x]

使用列表理解来迭代、过滤和变换树中的节点.

也可以写成map()代码>filter():

def tree_cut(tree):返回列表(地图(树切割,过滤器(无,树)))

if x 部分 测试列表是否为空.

>>>树 = [[[[], []], [[], []]], [[], [], []]]>>>树切割(树)[[[], []], []]

I have this exercise:

You have a tree graph as input, and you need to remove its leaves. So you need to remove the empty lists from a list of lists.

For example this:

[[[[], []], [[], []]], [[], [], []]]

becomes this: [[[], []], []]

I tried to use pop and del, but the teacher said to use recursion. Also it gives None as an output. But I can't figure out how to. Can you explain it how to or can you help to solve this question?

  def tree_cut(tree):
  for i in range(len(tree)):
      if tree[i]=="":
          tree.pop(i)
          return tree
          for k in tree[i]=="":
              if k=="":
                  tree.remove(k)
                  return tree

The solution:

def tree_cut(tree):
    return [tree_cut(x) for x in tree if x]

uses a list comprehension to iterate, filter and transform nodes in the tree.

Can be written also in terms of map() and filter():

def tree_cut(tree):
    return list(map(tree_cut, filter(None, tree)))

The if x part tests if the list is not empty.

>>> tree = [[[[], []], [[], []]], [[], [], []]]
>>> tree_cut(tree)
[[[], []], []]