python - 是否可以通过 Python 中的另一个字符串列表过滤子字符串列表?

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

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

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

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

结果应该是:

result = ['b', 'c']

最佳答案

你可以使用类似的东西:

[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']

https://stackoverflow.com/questions/46028725/

相关文章:

node.js - 如何在 Node.js 中设置文件编码

python - 无法将字节连接到 str(转换为 Python3)

angularjs - ngrx 参数选择函数

amazon-web-services - aws s3 ls 递归 grep 扩展 '.mov'

php - Laravel - 如何每分钟运行一个函数/ Controller ? (任务调度)

scala - 为什么我不能在 Scala 中增加?

r - 使用 ggplot 的条形图重新排序无法正常工作

nginx - 来自 nginx 的 422 状态代码的响应缺少 'Access-Control-A

macos - `open -a Chrome` 返回 `Unable to find applic

python - Python 中的 str.join() 和 str().join() 有什么区别