advice : how do you iterate with an acc ?

Dan Sommers me at privacy.net
Fri Dec 2 21:31:50 EST 2005


On 2 Dec 2005 16:45:38 -0800,
vd12005 at yahoo.fr wrote:

> hello,
> i'm wondering how people from here handle this, as i often encounter
> something like:

> acc = []    # accumulator ;)
> for line in fileinput.input():
>     if condition(line):
>         if acc:    #1
>             doSomething(acc)    #1
>         acc = []
>     else:
>         acc.append(line)
> if acc:    #2
>     doSomething(acc)    #2

> BTW i am particularly annoyed by #1 and #2 as it is a reptition, and i
> think it is quite error prone, how will you do it in a pythonic way ?

If doSomething handled an empty list gracefully, then you would have
less repetition:

    acc = []
    for line in fileinput.input():
        if condition(line):
            doSomething(acc)    #1
            acc = []
        else:
            acc.append(line)
    doSomething(acc)    #2

If condition were simple enough and the file(s) small enough, perhaps
you could read the whole file at once and use split to separate the
pieces:

    contents = file.read()
    for acc in contents.split( "this is the delimiter line\n" ):
        doSomething(acc.split("\n"))

(There are probably some strange cases of repeated delimiter lines or
delimiter lines occurring at the beginning or end of the file for which
the above code will not work.  Caveat emptor.)

If condition were a little more complicated, perhaps re.split would
work.

Or maybe you could look at split and see what it does (since your code
is conceptually very similar to it).

OTOH, FWIW, your version is very clean and very readable and fits my
brain perfectly.

HTH,
Dan

-- 
Dan Sommers
<http://www.tombstonezero.net/dan/>



More information about the Python-list mailing list