Python|从列表中删除空元组
在本文中,我们将看到如何从给定的元组列表中删除一个空元组。我们将找到各种方法,在其中我们可以使用Python中的各种方法和方式来执行删除元组的任务。
例子:
Input : tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'),
('krishna', 'akbar', '45'), ('',''),()]
Output : [('ram', '15', '8'), ('laxman', 'sita'),
('krishna', 'akbar', '45'), ('', '')]
Input : tuples = [('','','8'), (), ('0', '00', '000'),
('birbal', '', '45'), (''), (), ('',''),()]
Output : [('', '', '8'), ('0', '00', '000'), ('birbal', '',
'45'), ('', '')]
方法一:使用列表理解的概念
# Python program to remove empty tuples from a
# list of tuples function to remove empty tuples
# using list comprehension
def Remove(tuples):
tuples = [t for t in tuples if t]
return tuples
# Driver Code
tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'),
('krishna', 'akbar', '45'), ('',''),()]
print(Remove(tuples))
输出:
[('ram', '15', '8'), ('laxman', 'sita'), ('krishna',
'akbar', '45'), ('', '')]
方法二:使用 filter() 方法
使用Python中的内置方法 filter() ,我们可以通过传递None作为参数来过滤掉空元素。此方法适用于Python 2 和Python 3 及更高版本,但所需的输出仅在Python 2 中显示,因为Python 3 返回一个生成器。 filter() 比列表理解的方法更快。让我们看看当我们在Python 2 中运行程序时会发生什么。
# Python2 program to remove empty tuples
# from a list of tuples function to remove
# empty tuples using filter
def Remove(tuples):
tuples = filter(None, tuples)
return tuples
# Driver Code
tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'),
('krishna', 'akbar', '45'), ('',''),()]
print Remove(tuples)
输出:
[('ram', '15', '8'), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('', '')]
现在让我们看看当我们尝试在Python 3 及更高版本中运行程序时会发生什么。在Python 3 中运行程序时,如前所述,将返回一个生成器。
# Python program to remove empty tuples from
# a list of tuples function to remove empty
# tuples using filter
def Remove(tuples):
tuples = filter(None, tuples)
return tuples
# Driver Code
tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'),
('krishna', 'akbar', '45'), ('',''),()]
print (Remove(tuples))
输出: