【问题标题】:Comparing two lists similar to startswith比较两个类似于startswith的列表
【发布时间】:2018-01-15 09:37:32
【问题描述】:

我正在尝试编写简单的逻辑,该逻辑将在一个列表中查找以其他列表中的单词开头的单词。例如:

a = ["let","test","g"]
b = ["letter", "testing","good","egg","protest"]

应该返回:letter, testing, good

我已经涉足.startswith(),但它似乎无法使用整个列表进行搜索。也尝试过:

if any(i in a for i in b):

但我无法得到任何结果。

【问题讨论】:

    标签: python string python-2.7 list startswith


    【解决方案1】:

    str.startswith() 接受一个元组:

    >>> a = ["let","test","g"]
    >>> b = ["letter", "testing","good","egg","protest"]
    >>> a = tuple(a)
    >>> [item for item in b if item.startswith(a)]
    ['letter', 'testing', 'good']
    

    【讨论】:

    • 感谢您澄清这一点。是的,我可以简单地使用 .startswith 并且它可以工作。
    【解决方案2】:

    您可以通过列表理解来做到这一点:

    >>> [y for x in a for y in b if y.startswith(x)]
    ['letter', 'testing', 'good']
    

    您需要遍历这两个列表,然后检查列表 a 中的元素是否是列表 b 中对象的开头。

    如果您只需要它进行条件测试,最好使用生成器。这将在列表中的第一个匹配项上停止:

    >>> gen_exp = (y for x in a for y in b if y.startswith(x))
    >>> if any(gen_exp):
            __ your logic here __
    

    【讨论】:

      【解决方案3】:

      如果要查找b 中第一个以某个字符串开头的元素,可以使用next

      word = next(bword for bword in b if bword.startswith(aword))
      

      如果b中没有这个词,你可以提供一个默认值

      word = next((bword for bword in b if bword.startswith(aword)), None)
      

      要将其应用于a 的每个元素,您可以使用列表推导式。

      words = [next((bword for bword in b if bword.startswith(aword)), None) for aword in a]
      

      这会产生:

      ['letter', 'testing', 'good']
      

      【讨论】:

        【解决方案4】:

        我更喜欢在这种情况下使用itertools 模块:

        >>> [value for (start, value) in itertools.product(a,b) if value.startswith(start)]
        ['letter', 'testing', 'good']
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-06-19
          • 2021-02-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-15
          相关资源
          最近更新 更多