检查一个Python列表项是否包含另一个字符串内的字符串
我有一个列表:
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
并且想要搜索包含字符串'abc' 。 我怎样才能做到这一点?
if 'abc' in my_list:
会检查列表中是否存在'abc' ,但它是'abc-123'和'abc-456' , 'abc'不存在。 那么我怎样才能得到所有包含'abc'呢?
如果您只想检查列表中任何字符串中是否存在abc ,则可以尝试
some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
if any("abc" in s for s in some_list):
# whatever
如果你真的想获得所有包含abc的项目,请使用
matching = [s for s in some_list if "abc" in s]
使用filter来获取具有abc的元素。
>>> lst = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
>>> print filter(lambda x: 'abc' in x, lst)
['abc-123', 'abc-456']
你也可以使用列表理解。
>>> [x for x in lst if 'abc' in x]
顺便说一下,不要将单词list用作变量名称,因为它已经用于list类型。
只要把它抛出去:如果你碰巧需要匹配多个字符串,比如abc和def ,你可以把两个列表def结合起来,如下所示:
matchers = ['abc','def']
matching = [s for s in my_list if any(xs in s for xs in matchers)]
输出:
['abc-123', 'def-456', 'abc-456']
链接地址: http://www.djcxy.com/p/55063.html
上一篇: Check if a Python list item contains a string inside another string
下一篇: Compare strings in python like the sql "like" (with "%" and "
