简体   繁体   中英

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]

You'll have to post-process the resulting list (and convert the result to a list, per Ashwini's comment):

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

You can also pass your original list comprehension as the 2nd argument:

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

The first is probably more efficient if you expect many of the substitutions to produce empty strings.


Here's a solution using itertools and functools , for functional-style fans:

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

You can check for alpha characters in the word:

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

This can already be faster than the other approaches (it depends on whether there are words that become empty strings), but then you might as well not use the regular expression:

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

This is quite faster (tested on Python 2.7) and, in my opinion, doesn't hurt readability much, although it is a bit uglier than in Python 2.7, where I originally tested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM