Python 3:从元组列表中删除一个空的元组 [英] Python 3: Removing an empty tuple from a list of tuples

查看:898
本文介绍了Python 3:从元组列表中删除一个空的元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的元组列表:

I have a list of tuples that reads as such:

>>>myList
[(), (), ('',), ('c', 'e'), ('ca', 'ea'), ('d',), ('do',), ('dog', 'ear', 'eat', 'cat', 'car'), ('dogs', 'cars', 'done', 'eats', 'cats', 'ears'), ('don',)]

我希望这样读:

>>>myList
[('',), ('c', 'e'), ('ca', 'ea'), ('d',), ('do',), ('dog', 'ear', 'eat', 'cat', 'car'), ('dogs', 'cars', 'done', 'eats', 'cats', 'ears'), ('don',)]

即我想从列表中删除空元组().在执行此操作时,我想保留元组('',).我似乎找不到从列表中删除这些空元组的方法.

i.e. I would like to remove the empty tuples () from the list. While doing this I want to preserve the tuple ('',). I cannot seem to find a way to remove these empty tuples from the list.

我尝试了myList.remove(())并使用for循环来执行此操作,但是这不起作用或语法错误.任何帮助将不胜感激.

I have tried myList.remove(()) and using a for loop to do it, but either that doesn't work or I am getting the syntax wrong. Any help would be appreciated.

推荐答案

您可以过滤空"值:

filter(None, myList)

或者您可以使用列表推导.在Python 3上,filter()返回一个生成器; list comprehension返回有关Python 2或3的列表:

or you can use a list comprehension. On Python 3, filter() returns a generator; the list comprehension returns a list on either Python 2 or 3:

[t for t in myList if t]

如果列表中不仅包含元组,还可以显式测试空元组:

If your list contains more than just tuples, you could test for empty tuples explicitly:

[t for t in myList if t != ()]

Python 2演示:

Python 2 demo:

>>> myList = [(), (), ('',), ('c', 'e'), ('ca', 'ea'), ('d',), ('do',), ('dog', 'ear', 'eat', 'cat', 'car'), ('dogs', 'cars', 'done', 'eats', 'cats', 'ears'), ('don',)]
>>> filter(None, myList)
[('',), ('c', 'e'), ('ca', 'ea'), ('d',), ('do',), ('dog', 'ear', 'eat', 'cat', 'car'), ('dogs', 'cars', 'done', 'eats', 'cats', 'ears'), ('don',)]
>>> [t for t in myList if t]
[('',), ('c', 'e'), ('ca', 'ea'), ('d',), ('do',), ('dog', 'ear', 'eat', 'cat', 'car'), ('dogs', 'cars', 'done', 'eats', 'cats', 'ears'), ('don',)]
>>> [t for t in myList if t != ()]
[('',), ('c', 'e'), ('ca', 'ea'), ('d',), ('do',), ('dog', 'ear', 'eat', 'cat', 'car'), ('dogs', 'cars', 'done', 'eats', 'cats', 'ears'), ('don',)]

在这些选项中,filter()功能最快:

Of these options, the filter() function is fastest:

>>> timeit.timeit('filter(None, myList)', 'from __main__ import myList')
0.637274980545044
>>> timeit.timeit('[t for t in myList if t]', 'from __main__ import myList')
1.243359088897705
>>> timeit.timeit('[t for t in myList if t != ()]', 'from __main__ import myList')
1.4746298789978027

在Python 3上,请坚持使用列表理解:

On Python 3, stick to the list comprehension instead:

>>> timeit.timeit('list(filter(None, myList))', 'from __main__ import myList')
1.5365421772003174
>>> timeit.timeit('[t for t in myList if t]', 'from __main__ import myList')
1.29734206199646

这篇关于Python 3:从元组列表中删除一个空的元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆