根据内容过滤字符串列表

问题:根据内容过滤字符串列表

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

Given the list ['a','ab','abc','bac'], I want to compute a list with strings that have 'ab' in them. I.e. the result is ['ab','abc']. How can this be done in Python?


回答 0

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

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

另一种方法是使用该filter功能。在Python 2中:

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

在Python 3中,它返回一个迭代器而不是列表,但是您可以强制转换它:

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

尽管使用理解是更好的做法。

This simple filtering can be achieved in many ways with Python. The best approach is to use “list comprehensions” as follows:

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

Another way is to use the filter function. In Python 2:

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

In Python 3, it returns an iterator instead of a list, but you can cast it:

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

Though it’s better practice to use a comprehension.


回答 1

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

回答 2

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

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

filter(lambda x: x.startswith(prefix), items)
# To support matches from the beginning, not any matches:

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

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

回答 3

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

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

为什么这样做?因为为字符串定义了in运算符,以表示:“是”的子字符串。

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

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

Tried this out quickly in the interactive shell:

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

Why does this work? Because the in operator is defined for strings to mean: “is substring of”.

Also, you might want to consider writing out the loop as opposed to using the list comprehension syntax used above:

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

回答 4

mylist = ['a', 'ab', 'abc']
assert 'ab' in mylist
mylist = ['a', 'ab', 'abc']
assert 'ab' in mylist