根据内容过滤字符串列表

时间:2022-05-26 22:20:49

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?

有了这个列表(a, ab, abc, bac),我想计算一个包含ab的字符串的列表。也就是说,结果是['ab','abc']。如何在Python中实现这一点?

5 个解决方案

#1


80  

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

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

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

Another way is to use the filter function:

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

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

#2


13  

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

#3


8  

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

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

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

#4


3  

Tried this out quickly in the interactive shell:

在交互式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".

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

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)

#5


0  

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

#1


80  

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

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

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

Another way is to use the filter function:

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

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

#2


13  

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

#3


8  

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

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

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

#4


3  

Tried this out quickly in the interactive shell:

在交互式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".

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

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)

#5


0  

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