Python如何从列表中删除空元组?

2021年3月20日15:51:14 发表评论 872 次浏览

在本文中, 我们将看到如何从给定的元组列表中删除一个空的元组。我们将找到各种方法, 可以使用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'), ('', '')]

推荐:请尝试以下方法{IDE}首先, 在继续解决方案之前。

方法1:使用的概念清单理解

# 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'), ('', '')]

方法2:使用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))

输出如下:

<filter object at 0x7fe26eb0f3c8>

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: