开发手册 欢迎您!
软件开发者资料库

Python 删除list列表中出现的任何空列表的方法

本文主要介绍Python中,删除一个list列表中出现的任何空列表的方法,以及相关示例代码。

示例列表;

i = [[1,2,3,[]],[],[],[],[4,5,[],7]]

输出结果:

[[1,2,3],[4,5,7]]

1、使用递归实现

使用递归,可以删除任何深度的空列表:

def remove_nested_list(listt):
for index, value in enumerate(reversed(listt)):
if isinstance(value, list) and value != []:
remove_nested_list(value)
elif isinstance(value, list) and len(value) == 0:
listt.remove(value)

a = [[1, 2, 3, 0, []], [], [], [], [4, 5, [], 7]]
print(f"before-->{a}")
remove_nested_list(a)
print(f"after-->{a}")

输出:

before-->[[1, 2, 3, 0, []], [], [], [], [4, 5, [], 7]]
after-->[[1, 2, 3, 0], [4, 5, 7]]

或者

a = [[1,2,3,[]],[],[],[],[4,5,[],7]]def nested_check(alist):    for item in alist[:]:        if item == []:            alist.remove(item)        elif isinstance(item, list):            nested_check(item)nested_check(a)print(a)

或者

def empty(lst):    if lst == []:        return True    elif isinstance(lst, list):        return all(empty(i) for i in lst)    else:        return Falsedef remove_empty(lst):    return (        [remove_empty(i) for i in lst if not empty(i)]        if isinstance(lst, list)        else lst    )i = [[1,2,3,[]],[],[],[],[4,5,[],7]]remove_empty(i)remove_nested_list(i) print(i) # [[1, 2, 3, []]]ii = [[1,2,3,[]],[],[],[],[4,5,[],7]]remove_empty(ii)remove_nested_list(ii) print(ii) 

2、确定深度的方法

i = [[1,2,3,[]],[],[],[],[4,5,[],7]]
print([[j for j in ele if j] for ele in i if ele])

或者

a = [[1,2,3,[]],[],[],[],[4,5,[],7]]print('list before:', a)while [] in a:    for i in a:        if i == []:            a.remove(i)for i in a:    for e in i:        if e == []:            i.remove(e)print('list after:', a)