Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #13126
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Subject | Re: Idioms combining 'next(items)' and 'for item in items:' |
| Date | 2011-09-11 15:41 +0200 |
| Organization | None |
| References | <j4gea4$m3b$1@dough.gmane.org> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.988.1315748478.27778.python-list@python.org> (permalink) |
Terry Reedy wrote:
> 3. Process the items of an iterable in pairs.
>
> items = iter(iterable)
> for first in items:
> second = next(items)
> <process first and second>
>
> This time, StopIteration is raised for an odd number of items. Catch and
> process as desired. One possibility is to raise ValueError("Iterable
> must have an even number of items").
Another way is zip-based iteration:
(a) silently drop the odd item
items = iter(iterable)
for first, second in zip(items, items): # itertools.izip in 2.x
...
(b) add a fill value
for first, second in itertools.zip_longest(items, items):
...
(c) raise an exception
Unfortunately there is no zip_exc() that guarantees that all iterables are
of the same "length", but I've written a recipe some time ago
http://code.activestate.com/recipes/497006-zip_exc-a-lazy-zip-that-ensures-
that-all-iterables/
that achieves near-C speed.
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Idioms combining 'next(items)' and 'for item in items:' Peter Otten <__peter__@web.de> - 2011-09-11 15:41 +0200
csiph-web