关于python:使用列表推导过滤字符串列表

Filter list of strings using list comprehension

1
2
3
4
>>> li = ["a b self","mpilgrim","foo c","b","c","b","d","d"]
>>> condition = ["b","c","d"]
>>> [elem for elem in li if elem in condition]
['b', 'c', 'b', 'd', 'd']

但是有返回的方法吗

1
['a b self','foo c','b', 'c', 'b', 'd', 'd']

由于b和c包含在'a b self''foo c'中,所以我希望代码也返回这两个值。


假设代码需要检索包含任何条件字符串的所有字符串:

1
[elem for elem in li if any(c in elem for c in condition)]

如果需要完全匹配某个条件:

1
2
[elem for elem in li if
 any(re.search('(^|\s){}(\s|$)'.format(c), elem) for c in condition)]

编辑:这可以简化为一个预先定义的regex:

1
2
3
predicate = re.compile('(^|\s)({})(\s|$)'.format('|'.join(condition)))

[elem for elem in li if predicate.search(elem)]