Accessing next/prev element while for looping
Alex Martelli
aleax at mail.comcast.net
Sun Dec 18 11:12:37 EST 2005
Steven D'Aprano <steve at REMOVETHIScyber.com.au> wrote:
> I can't speak for others, but I've never come upon a situation where I
> needed to access the element before and the element after the current one.
>
> [thinks...] Wait, no, there was once, when I was writing a parser that
> iterated over lines. I needed line continuations, so if the line ended
> with a backslash, I needed to access the next line (and potentially the
> line after that, and so forth indefinitely). I dealt with that by keeping
> a cache of lines seen, adding to the cache if the line ended with a
> backslash.
In Python, that would be an excellent example use case for a generator
able to "bunch up" input items into output items, e.g.:
def bunch_up(seq):
cache = []
for item in seq:
if item.endswith('\\\n'):
cache.append(item[:-2])
else:
yield ''.join(cache) + item
cache = []
if cache:
raise ValueError("extra continuations at end of sequence")
[[or whatever you wish to do instead of raising if the input sequence
anomalously ends with a ``to be continued'' line]].
Alex
More information about the Python-list
mailing list