istep() addition to itertool? (Was: Re: Printing n elements per line in a list)
Neil Cerutti
horpner at yahoo.com
Mon Aug 21 10:42:46 EDT 2006
On 2006-08-19, Rhamphoryncus <rhamph at gmail.com> wrote:
> unexpected wrote:
>> If have a list from 1 to 100, what's the easiest, most elegant
>> way to print them out, so that there are only n elements per
>> line.
>
> I've run into this problem a few times, and although many
> solutions have been presented specifically for printing I would
> like to present a more general alternative.
>
> from itertools import chain
> def istepline(step, iterator):
> i = 0
> while i < step:
> yield iterator.next()
> i += 1
>
> def istep(iterable, step):
> iterator = iter(iterable) # Make sure we won't restart iteration
> while True:
> # We rely on istepline()'s side-effect of progressing the
> # iterator.
> start = iterator.next()
> rest = istepline(step - 1, iterator)
> yield chain((start,), rest)
> for i in rest:
> pass # Exhaust rest to make sure the iterator has
> # progressed properly.
>
> Would anybody else find this useful? Maybe worth adding it to
> itertool?
Your note me curious enough to re-read the itertools
documentation, and I found the following in 5.16.3 Recipes:
def grouper(n, iterable, padvalue=None):
"grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)
Wish I'd found that yesterday. ;)
--
Neil Cerutti
More information about the Python-list
mailing list