Good Python generators example?

Aahz aahz at pythoncraft.com
Sun Apr 20 23:34:20 CEST 2003


In article <paDoa.1611$hT2.1228371 at news2.news.adelphia.net>,
Robert Oschler <no_replies at fake_email_address.invalid> wrote:
>
>Can someone point me to a nice concise Python 2.2 compatible example of the
>use of generators?

ARK's example was a good example of the algorithmic use of generators;
here's a short example of what I'd call workday use of generators:

import re
def grep(regex, seq):
    '''
    regex can be either string or compiled regex; ``re`` doesn't care.  
    seq can be an iterator -- there's just no good abbreviation other
    than iter()
    '''

    regex = re.compile(regex)
    for line in seq:
        if regex.search(line):
            yield line

The nice thing about this is that it pipelines *very* well with other
generators.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

Why is this newsgroup different from all other newsgroups?




More information about the Python-list mailing list