On 2006-08-19, Rhamphoryncus <[EMAIL PROTECTED]> 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 -- http://mail.python.org/mailman/listinfo/python-list