簡體   English   中英

過濾列表理解

[英]Filter in list comprehension

是否可以向此列表理解添加條件,以使其結果不包含空字符串:

words = [regex.sub('\P{alpha}','',word) for word in words]

將其移動到生成器表達式中,並對其進行列表理解。

words = [x for x in (regex.sub('\P{alpha}', '', word) for word in words) if x]

您必須對結果列表進行后處理(根據Ashwini的評論,並將結果轉換為列表):

words = list(filter(None, (regex.sub('\P{alpha}','',word) for word in words)))

您還可以將原始列表理解作為第二個參數傳遞:

words = filter(None, [regex.sub('\P{alpha}','',word) for word in words])

如果您期望許多替換產生空字符串,則第一個可能會更有效。


這是針對功能性風扇的使用itertoolsfunctools的解決方案:

from itertools import imap, filter
from functools import partial
modifier = partial(regex.sub, '\P{alpha}', '')
words = list(ifilter(None, imap(modifier, words)))

您可以檢查單詞中的字母字符:

[regex.sub('\P{alpha}','',word) for word in words if list(filter(str.isalpha, word))]

這可能已經比其他方法要快(取決於是否有單詞變成空字符串),但是您也可能不使用正則表達式:

[x for x in ("".join(filter(str.isalpha, word)) for word in words) if x]

這相當快(在Python 2.7上測試),並且在我看來,並沒有很大地損害可讀性,盡管它比我最初測試的Python 2.7難看。

暫無
暫無

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

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