Python如何从列表中删除空列表?代码示例

有时, 在处理python数据时, 我们可能会遇到一个问题, 我们需要过滤掉某些空数据。这些可以是None, 空字符串等。这可以在许多域中应用。让我们讨论可以删除空列表的某些方法

 

方法1:使用列表理解

这是可以解决此问题的方法之一。在此, 我们遍历列表, 不包括空列表。

# Python3 code to demonstrate 
# Remove empty List from List
# using list comprehension
  
# Initializing list 
test_list = [ 5 , 6 , [], 3 , [], [], 9 ]
  
# printing original list 
print ( "The original list is : " + str (test_list))
  
# Remove empty List from List
# using list comprehension
res = [ele for ele in test_list if ele ! = []]
  
# printing result 
print ( "List after empty list removal : " + str (res))

输出:

The original list is : [5, 6, [], 3, [], [], 9]
List after empty list removal : [5, 6, 3, 9]

 

方法2:使用filter()

这是可以执行此任务的另一种方法。在此, 我们过滤None值。 none值也包括空列表, 因此将其删除。

# Python3 code to demonstrate 
# Remove empty List from List
# using filter()
  
# Initializing list 
test_list = [ 5 , 6 , [], 3 , [], [], 9 ]
  
# printing original list 
print ( "The original list is : " + str (test_list))
  
# Remove empty List from List
# using filter
res = list ( filter ( None , test_list))
  
# printing result 
print ( "List after empty list removal : " + str (res))

输出:

The original list is : [5, 6, [], 3, [], [], 9]
List after empty list removal : [5, 6, 3, 9]

更多Python开发相关内容请参考:lsbin - IT开发技术https://www.lsbin.com/

查看以下更多Python相关的内容:

  • 10
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值