有时, 在处理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相关的内容: