使用列表推导过滤字符串列表

时间:2017-04-29 14:44:56

标签: python list-comprehension

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

但有没有办法返回

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

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

1 个答案:

答案 0 :(得分:4)

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

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

如果需要完全符合条件:

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

修改:这可以简化为单个预定义的正则表达式:

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

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