使用列表推导过滤字符串列表 [英] Filter list of strings using list comprehension

查看:73
本文介绍了使用列表推导过滤字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> 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'中,所以我希望代码也返回两者.

Since b and c are included in 'a b self' and 'foo c', I want the code to return the two as well.

推荐答案

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

Assuming the code needs to retrieve all the strings that contain any of the conditions strings:

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

如果需要完全匹配条件:

In case a full match of a condition is required:

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

编辑:可以将其简化为单个预定义的正则表达式:

Edit: This can be simplified to a single pre-defined regex:

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

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

这篇关于使用列表推导过滤字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆