Last iteration?
Peter Otten
__peter__ at web.de
Wed Oct 17 04:03:27 EDT 2007
Raymond Hettinger wrote:
> [Diez B. Roggisch]
>> > out:) But I wanted a general purpose based solution to be available that
>> > doesn't count on len() working on an arbitrary iterable.
>
> [Peter Otten]
>> You show signs of a severe case of morbus itertools.
>> I, too, am affected and have not yet fully recovered...
>
> Maybe you guys were secretly yearning for a magical last element
> detector used like this:
Not secretly...
> def lastdetecter(iterable):
> it = iter(iterable)
> value = it.next()
> for nextvalue in it:
> yield (False, value)
> value = nextvalue
> yield (True, value)
as that's what I posted above...
> def lastdetecter(iterable):
> "fast iterator algebra"
> lookahead, t = tee(iterable)
# make it cope with zero-length iterables
lookahead = islice(lookahead, 1, None)
> return chain(izip(repeat(False), imap(itemgetter(1),
> izip(lookahead, t))), izip(repeat(True),t))
and that's the "somebody call the doctor -- now!" version ;)
Peter
More information about the Python-list
mailing list