【问题标题】:Is it possible to filter list of substrings by another list of strings in Python?是否可以通过 Python 中的另一个字符串列表过滤子字符串列表?
【发布时间】:2018-02-12 04:48:25
【问题描述】:

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

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

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

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

结果应该是:

result = ['b', 'c']

【问题讨论】:

  • 带有简单的列表理解:[i for i in substrings for j in strings if i in j]

标签: python arrays string list numpy


【解决方案1】:

你可以使用类似的东西:

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

【讨论】:

  • 试图在我的一个函数中使用它,但它给出了 TypeError: a bytes-like object is required, not 'str' 。你能提出一个解决方案吗
【解决方案2】:

实现这一点的优雅方法是使用带有 列表理解any

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

>>> [s for s in substrings if any(s in i for i in my_strings)]
['b', 'c']

如果substrings 中的任何字符串作为my_strings 中的子字符串存在,则此处any 将返回True。一旦找到匹配项,它将使迭代短路(不检查其他匹配项)并将结果返回为True。由于any 的短路特性,它不会对整个列表进行不必要的迭代,从而获得更好的性能。

【讨论】:

    猜你喜欢
    • 2019-08-03
    • 1970-01-01
    • 2017-04-23
    • 2021-08-09
    • 1970-01-01
    • 2012-11-23
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多