python如何删除列表中的空列表
可以使用列表推导式,通过判断子列表的长度来过滤掉空列表:
lst = [ [1, 2], [], [3, 4], [], [], [5, 6] ]
lst = [sublst for sublst in lst if len(sublst) > 0]
print(lst) # 输出 [[1, 2], [3, 4], [5, 6]]
或者使用循环遍历并删除空列表:
lst = [ [1, 2], [], [3, 4], [], [], [5, 6] ]
i = 0
while i < len(lst):
if len(lst[i]) == 0:
del lst[i]
else:
i += 1
print(lst) # 输出 [[1, 2], [3, 4], [5, 6]]
原文地址: https://www.cveoy.top/t/topic/nCR 著作权归作者所有。请勿转载和采集!