advice : how do you iterate with an acc ?
Ben Finney
bignose+hates-spam at benfinney.id.au
Sat Dec 3 03:20:14 EST 2005
vd12005 at yahoo.fr wrote:
> 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
Looks like you'd be better off making an Accumulator that knows what
to do.
>>> class Accumulator(list):
... def flush(self):
... if len(self):
... print "Flushing items: %s" % self
... del self[:]
...
>>> lines = [
... "spam", "eggs", "FLUSH",
... "beans", "rat", "FLUSH",
... "strawberry",
... ]
>>>
>>> acc = Accumulator()
>>> for line in lines:
... if line == 'FLUSH':
... acc.flush()
... else:
... acc.append(line)
...
Flushing items: ['spam', 'eggs']
Flushing items: ['beans', 'rat']
>>> acc.flush()
Flushing items: ['strawberry']
>>>
--
\ "[W]e are still the first generation of users, and for all that |
`\ we may have invented the net, we still don't really get it." |
_o__) -- Douglas Adams |
Ben Finney
More information about the Python-list
mailing list