根据内容过滤字符串列表

时间:2010-01-28 07:17:42

标签: python list

鉴于列表['a','ab','abc','bac'],我想计算一个包含'ab'字符串的列表。即结果是['ab','abc']。如何在Python中完成?

5 个答案:

答案 0 :(得分:107)

这种简单的过滤可以通过Python以多种方式实现。最好的方法是使用“list comprehensions”如下:

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

另一种方法是使用filter函数:

>>> filter(lambda k: 'ab' in k, lst)
['ab', 'abc']
>>> 

答案 1 :(得分:15)

[x for x in L if 'ab' in x]

答案 2 :(得分:8)

# To support matches from the beginning, not any matches:

items = ['a', 'ab', 'abc', 'bac']
prefix = 'ab'

filter(lambda x: x.startswith(prefix), items)

答案 3 :(得分:4)

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

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

为什么这样做?因为in operator是为字符串定义的意思:“是子串的”。

另外,您可能需要考虑写出循环而不是使用上面使用的list comprehension syntax

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

答案 4 :(得分:0)

mylist = ['a', 'ab', 'abc']
assert 'ab' in mylist
相关问题