Loop in a loop?
George Sakkis
george.sakkis at gmail.com
Thu Jan 17 14:02:34 EST 2008
On Jan 17, 12:25 pm, Paul Hankin <paul.han... at gmail.com> wrote:
> On Jan 17, 4:38 pm, Bruno Desthuilliers <bruno.
>
> 42.desthuilli... at wtf.websiteburo.oops.com> wrote:
> > Now there are very certainly smart solutions using itertools, but the
> > one I cooked is way too ugly so I'll leave this to itertools masters !-)
>
> Here's my effort:
>
> from itertools import izip, islice, chain, repeat
>
> def padzip(*xs, **kw):
> pad = kw.get('padding', None)
> maxlen = max(len(x) for x in xs)
> return islice(izip(*[chain(x, repeat(pad)) for x in xs]), maxlen)
>
> --
> Paul Hankin
And if the iterables don't necessarily support len(), here's a more
general solution:
from itertools import repeat
def izippad(*iterables, **kw):
pad = kw.get('padding', None)
next_pad = repeat(pad).next
getnext = [iter(iterable).next for iterable in iterables]
pending = size = len(iterables)
while True:
slice = [None] * size
for i in xrange(size):
try: slice[i] = getnext[i]()
except StopIteration:
pending -= 1
if not pending: return
getnext[i] = next_pad
slice[i] = pad
yield slice
George
More information about the Python-list
mailing list