簡體   English   中英

Python 3:從元組列表中刪除空元組

[英]Python 3: Removing an empty tuple from a list of tuples

我有一個這樣的元組列表:

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

即我想從列表中刪除空的元組() 在執行此操作時,我想保留元組('',) 我似乎找不到從列表中刪除這些空元組的方法。

我已經嘗試過myList.remove(())並使用for循環來做到這一點,但是那還是行不通或者我弄錯了語法。 任何幫助,將不勝感激。

您可以過濾“空”值:

filter(None, myList)

或者您可以使用列表理解。 在Python 3上, filter()返回一個生成器; list comprehension返回有關Python 2或3的列表:

[t for t in myList if t]

如果列表中不僅包含元組,還可以顯式測試空元組:

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

Python 2演示:

>>> 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()函數最快:

>>> 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上,請堅持使用列表理解:

>>> 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
myList = [x for x in myList if x != ()]

使用列表推導來過濾出空的元組:

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

之所以可行,是因為在Python中空元組的值為False

顯式勝於隱式

通過明確指定過濾器的功能,我發現此代碼更具可讀性,並且不模糊。 所以很明顯,我們想刪除那些空的元組()

def filter_empty_tuple(my_tuple_list):
    return filter(lambda x: x != (), my_tuple_list)

# convert to list
def filter_empty_tuple_to_list(my_tuple_list):
    return list(filter(lambda x: x != (), my_tuple_list))

如果您不將它們轉換為list並將其用作generator則可能會很好。 在決定使用哪個時請參閱此問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM