📜  Python|从列表中删除空元组(1)

📅  最后修改于: 2023-12-03 14:46:25.431000             🧑  作者: Mango

Python | 从列表中删除空元组

在Python编程中,我们经常需要从一个列表中删除空元组。一个空元组是指在列表中,元组中没有任何元素。这个任务可以通过一些简单的方法完成。在本文中,我们将讨论如何在Python中从列表中删除空元组,并提供相应的代码示例。

方法一:使用for循环

首先,我们可以使用for循环遍历列表,检查每个元组是否为空,并将其从列表中删除。以下是该方法的示例代码:

# Sample Python code to delete empty tuples from a list

# List having empty tuple
test_list = [(), ('a', 'b'), ('c', 'd'), (), ('e',), ('',)]

# printing original list
print("The original list is : " + str(test_list))

# using filter() + lambda
# to remove empty tuples
res_list = list(filter(lambda x: x != (), test_list))

# printing resultant list
print("List after empty tuple removal : " + str(res_list))

输出结果:

The original list is : [(), ('a', 'b'), ('c', 'd'), (), ('e',), ('',)]
List after empty tuple removal : [('a', 'b'), ('c', 'd'), ('e',), ('',)]

在这段代码中,我们首先创建一个包含空元组的列表。然后,我们使用filter()函数和lambda表达式来过滤掉所有的空元组,并将结果保存在一个新的列表中。最后,我们打印新列表。

方法二:使用列表推导式

除了使用for循环和filter()函数来删除空元组之外,我们还可以使用一个更简单的方法:通过列表推导式。以下是该方法的示例代码:

# Sample Python code to delete empty tuples from a list

# List having empty tuple
test_list = [(), ('a', 'b'), ('c', 'd'), (), ('e',), ('',)]

# printing original list
print("The original list is : " + str(test_list))

# using list comprehension
# to remove empty tuples
res_list = [ele for ele in test_list if ele != ()]

# printing resultant list
print("List after empty tuple removal : " + str(res_list))

输出结果:

The original list is : [(), ('a', 'b'), ('c', 'd'), (), ('e',), ('',)]
List after empty tuple removal : [('a', 'b'), ('c', 'd'), ('e',), ('',)]

在这段代码中,我们使用列表推导式来遍历列表并检查每个元素是否为空元组。如果元素不是空元组,则将其添加到新列表中。最后,我们打印新列表。

结论

使用上述两种方法,我们可以在Python中轻松地从列表中删除空元组。不管你使用for循环或列表推导式,确保你的代码易于阅读和理解。