根据内容过滤string列表

给定列表['a','ab','abc','bac'] ,我想计算一个列表中有'ab'string。 即结果是['ab','abc'] 。 这怎么可以在Python中完成?

这个简单的过滤可以用Python以许多方式实现。 最好的方法是使用“列表parsing”,如下所示:

 >>> lst = ['a', 'ab', 'abc', 'bac'] >>> res = [k for k in lst if 'ab' in k] >>> res ['ab', 'abc'] >>> 

另一种方法是使用filterfunction:

 >>> filter(lambda k: 'ab' in k, lst) ['ab', 'abc'] >>> 
 [x for x in L if 'ab' in x] 
 # To support matches from the beginning, not any matches: list = ['a', 'ab', 'abc', 'bac'] prefix = 'ab' filter(lambda x: x.startswith(prefix), list) 

在交互式shell中快速尝试了这一点:

 >>> l = ['a', 'ab', 'abc', 'bac'] >>> [x for x in l if 'ab' in x] ['ab', 'abc'] >>> 

为什么这个工作? 因为in运算符是为string定义的:“是…的子string”。

另外,您可能需要考虑写出循环,而不是使用上面使用的列表理解语法 :

 l = ['a', 'ab', 'abc', 'bac'] result = [] for s in l: if 'ab' in s: result.append(s) 
 mylist = ['a', 'ab', 'abc'] assert 'ab' in mylist