Basj Basj - 1 year ago 92
Python Question

Find + Find next in Python

Let L be a list of strings.

Here is the code I use for finding a string

in the list L.

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

How would you do a Find next feature ? Do I need to store the index of the previously found string?

Answer Source

One approach for huge lists would be to use a generator. Suppose you do not know whether the user will need the next match.

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

The other answers suggesting list comprehensions are great for short lists when you want all results immediately. The nice thing about this approach is that if you never need the third result no time is wasted finding it. Again, it would really only matter for big lists.

Update: If you want the cycle to restart at the first match, you could do something like this...

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

See How to make a repeating generator for other ideas.

Another Update

It's been years since I first wrote this. Here's a better approach using 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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download