繁体   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