2010-01-28 36 views
45

鉴于列表['a','ab','abc','bac'],我想计算一个列表,其中包含'ab'的字符串。即结果是['ab','abc']。这怎么可以在Python中完成?根据内容过滤字符串列表

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

为什么这项工作:

+0

感谢礼Bendersky – 2010-01-28 08:33:41

+0

给出的列表[” a','b','c','a','b'],我想计算一个带有'a'和'b'的字符串列表。即结果是['a','b']。这怎么可以在Python中完成? – 2010-01-28 08:35:32

回答

71

这种简单的过滤可以在Python中的许多方式来实现。最好的方法是如下使用 “列表理解”:

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

-1:Lambda。请不要在n00bs上施加lambda。 – 2010-01-28 11:53:27

+26

@ S.Lott:为什么?在适当的环境中学习有用的高级编程主题有什么问题? – 2010-01-28 12:23:08

+0

@Edi Bendersky:因为他们比有用的更混乱?因为它会导致回答“使用def”的问题?因为它很少会比代码高尔夫更好吗?我不知道,经过30多年的各种语言编程之后,它们对我来说似乎毫无用处。但我想他们对你真的很重要。 – 2010-01-28 12:33:19

12
[x for x in L if 'ab' in x] 
+0

你赢了48秒:-) – 2010-01-28 07:20:34

3

在交互shell快速试过了这一点?因为in operator是为字符串定义的:“是...的子串”。

而且,你可能要考虑写出来的循环,而不是使用上面所用的list comprehension syntax

l = ['a', 'ab', 'abc', 'bac'] 
result = [] 
for s in l: 
    if 'ab' in s: 
     result.append(s) 
0
mylist = ['a', 'ab', 'abc'] 
assert 'ab' in mylist 
5
# To support matches from the beginning, not any matches: 

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

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