如何使用递归从列表中删除某些内容?Python [英] How to remove something from a list with recursion? Python

查看:32
本文介绍了如何使用递归从列表中删除某些内容?Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个练习:

您有一个树形图作为输入,您需要移除它的叶子.因此,您需要从列表列表中删除空列表.

例如这个:

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

变成这样:[[[], []], []]

我尝试使用pop和del,但老师说使用递归.它也给出 None 作为输出.但我不知道该怎么做.你能解释一下如何或者你能帮助解决这个问题吗?

 def tree_cut(tree):对于我在范围内(len(树)):如果树[i]=="":树.pop(i)返回树对于树中的 k[i]=="":如果 k=="":tree.remove(k)返回树

解决方案

解决方案:

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)
[[[], []], []]

这篇关于如何使用递归从列表中删除某些内容?Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆