advice : how do you iterate with an acc ?

Jeffrey Schwab jeff at schwabcenter.com
Sat Dec 3 08:08:07 CET 2005


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 ?

Could you add a sentry to the end of your input?  E.g.:

	for line in fileinput.input() + line_that_matches_condition:

This way, you wouldn't need a separate check at the end.



More information about the Python-list mailing list