Python 如何在嵌套列表中运行forloop,以便循环不断进入每个嵌套循环

Python 如何在嵌套列表中运行forloop,以便循环不断进入每个嵌套循环,python,python-3.x,Python,Python 3.x,我必须从列表中删除空列表,无论它们嵌套得有多深 示例a=[2,3,[4,4,5,6,5,6,5,5,5,5,6,5,4,4,4,5][3][3][3][3][3][3][3][3][3][4,4][3][3][3][3][3][3 期望的答案 b = [2, 3, [[4]] , 5, 6 ] 到目前为止我有 def delete_empty_list(x): b = [x for x in a if x != []] return(b) 这让我 b = [2, 3, [

我必须从列表中删除空列表,无论它们嵌套得有多深

示例
a=[2,3,[4,4,5,6,5,6,5,5,5,5,6,5,4,4,4,5][3][3][3][3][3][3][3][3][3][4,4][3][3][3][3][3][3

期望的答案

b = [2, 3, [[4]] , 5, 6 ]
到目前为止我有

def delete_empty_list(x):
   b = [x for x in a if x != []]    
   return(b)
这让我

b = [2, 3, [[[[[]]]]], [[4, []]], 5, 6]

我不知道如何在列表中的嵌套项中循环。此外,项目可以嵌套,无论我的函数的深度如何

您可以将递归与
过滤器一起使用:

a = [2, 3, [[[[[]]]]], [[4, []]] , 5, 6, [], [], []] 
def _filter(d):
  r = [c if not isinstance(c, list) else _filter(c) for c in d if c != []]
  return list(filter(lambda x:x != [], r))

print(_filter(a))
输出:

[2, 3, [[4]], 5, 6]

您可以使用递归:

def remove(lst):
    result = []
    for e in lst:
        if isinstance(e, list):
            l = remove(e)
            if l:
                result.append(l)
        else:
            result.append(e)
    return result


a = [2, 3, [[[[[]]]]], [[4, []]], 5, 6, [], [], []]

print(remove(a))
输出

[2, 3, [[4]], 5, 6]

其思想是检查元素是否是一个列表,然后在结果不是空的情况下对元素递归调用remove添加它。对于普通元素(不是列表),只需添加它们。

您可以使用以下递归函数来理解列表:

def f(a):
    return [i for l in a for i in [f(l) if isinstance(l, list) else l] if i != []]
以便:

f([2, 3, [[[[[]]]]], [[4, []]] , 5, 6, [], [], []])
返回:

[2, 3, [[4]], 5, 6]
您可以使用以下代码:

a = [2, 3, [[[[[]]]]], [[4, []]] , 5, 6, [], [], []]

def filter_function(e):
    if isinstance(e, list):
        return filter(None, map(filter_function, e))
    elif e != []:
        return e

print filter_function(a)

研究像递归这样的分治算法。