advice : how do you iterate with an acc ?
Scott David Daniels
scott.daniels at acm.org
Sat Dec 3 10:53:53 EST 2005
Jeffrey Schwab wrote:
> vd12005 at yahoo.fr wrote:
>> hello,
>>
>> .... 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
>
> 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.
Check itertools for a good way to do this:
import itertools
SENTRY = 'something for which condition(SENTRY) is True'
f = open(filename)
try:
for line in itertools.chain(f, [SENTRY]):
if condition(line):
if acc:
doSomething(acc)
acc = []
else:
acc.append(line)
assert acc == []
finally:
f.close()
--Scott David Daniels
scott.daniels at acm.org
More information about the Python-list
mailing list