本文介绍了是否可以用Python中的另一个字符串列表过滤子字符串列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要在Python中用另一个字符串列表过滤字符串列表,我们可以使用以下代码:

To filter list of strings by another list of strings in Python we can use the following code:

result = [x for x in strings1 if x in strings2]

但是我们如何通过另一个字符串列表来过滤子字符串列表呢?例如:

But how can we filter list of substrings by another list of strings? For example:

substrings = ['a', 'b', 'c']
strings = ['_b_', '_c_', '_d_']

结果应为:

result = ['b', 'c']

推荐答案

您可以使用类似的方法:

You can use something like that:

[x for x in substrings if [y for y in strings if x in y]]


In [1]: substrings = ['a', 'b', 'c']

In [2]: strings = ['_b_', '_c_', '_d_']

In [3]: [x for x in substrings if [y for y in strings if x in y]]
Out[3]: ['b', 'c']

这篇关于是否可以用Python中的另一个字符串列表过滤子字符串列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 14:01