【问题标题】:Find + Find next in Python在 Python 中查找 + 查找下一个
【发布时间】:2014-01-10 09:02:48
【问题描述】:

令 L 为字符串列表。

这是我用于在列表 L 中查找字符串 texttofind 的代码。

texttofind = 'Bonjour'
for s in L:
    if texttofind in s:
        print 'Found!'
        print s
        break

您将如何实现查找下一个功能?我需要存储之前找到的字符串的索引吗?

【问题讨论】:

    标签: python string


    【解决方案1】:

    如果存在,它将在下一个找到。您可以将其包装在函数中,如果没有,则返回 None/Empty 字符串。

    L = ['Hello', 'Hola', 'Bonjour', 'Salam']
    
    for l in L:
        if l == texttofind:
            print l
            if L.index(l) >= 0 and L.index(l) < len(L):
                print L[L.index(l)+1]
    

    【讨论】:

    • 这没有找到下一个,这个“下一个找到” - 它在匹配行之后的下一个
    【解决方案2】:

    如果要查找 L 中所有以 s 为子字符串的字符串索引,

    [i for i in range(0, len(L)) if L[i].find(s) >= 0]
    

    【讨论】:

      【解决方案3】:

      L 中查找所有以s 为子字符串的字符串。

      [f for f in L if s in f]
      

      【讨论】:

        【解决方案4】:

        大型列表的一种方法是使用生成器。假设您不知道用户是否需要下一个匹配项。

        def string_in_list(s, entities):
            """Return elements of entities that contain given string."""
            for e in entities:
                if s in e:
                    yield e
        
        huge_list = ['you', 'say', 'hello', 'I', 'say', 'goodbye']  # ...
        matches = string_in_list('y', huge_list)  # look for strings with letter 'y'
        next(matches)  # first match
        next(matches)  # second match
        

        当您想要立即获得所有结果时,建议列表理解的其他答案非常适合短列表。这种方法的好处是,如果您从不需要第三个结果,就不会浪费时间去寻找它。同样,它只对大列表很重要。

        更新:如果您希望循环在第一场比赛时重新开始,您可以这样做...

        def string_in_list(s, entities):
            idx = 0
            while idx < len(entities):
                if s in entities[idx]:
                    yield entities[idx]
                idx += 1
                if idx >= len(entities):
                    # restart from the beginning
                    idx = 0
        huge_list = ['you', 'say', 'hello']
        m = string_in_list('y', huge_list)
        next(m)  # you
        next(m)  # say
        next(m)  # you, again
        

        请参阅How to make a repeating generator 了解其他想法。

        另一个更新

        自从我第一次写这篇文章以来已经有好几年了。这是使用itertools.cycle 的更好方法:

        from itertools import cycle  # will repeat after end
        
        # look for s in items of huge_list
        matches = cycle(i for i in huge_list if s in i)
        next(matches)
        

        【讨论】:

        • 可以更简洁的写成matches = (line for line in L if s in line)
        • @Eric,感谢您指出这一点!我想这个函数只有在寻找匹配涉及更复杂的处理时才有用。
        • 如果我在代码中看到这个我会哭的。生成器表达式的完美候选者。
        • 谢谢。 matches = (line for line in L if s in line) 真的和 def ... yield 的代码一样吗?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-23
        • 1970-01-01
        • 2014-07-16
        • 1970-01-01
        相关资源
        最近更新 更多