Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find + Find next in Python

Tags:

python

string

Let L be a list of strings.

Here is the code I use for finding a string texttofind in the list L.

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

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

like image 879
Basj Avatar asked Apr 22 '26 06:04

Basj


1 Answers

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)
next(matches)
like image 137
ChrisP Avatar answered Apr 24 '26 22:04

ChrisP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!