Loop in a loop?
Duncan Booth
duncan.booth at invalid.invalid
Thu Jan 17 10:20:05 EST 2008
Chris <cwitts at gmail.com> wrote:
> You could always pre-pad the lists you are using before using the zip
> function, kinda like
>
> def pad(*iterables):
> max_length = 0
> for each_iterable in iterables:
> if len(each_iterable) > max_length: max_length =
> len(each_iterable)
> for each_iterable in iterables:
> each_iterable.extend([None for i in xrange(0,max_length-
> len(each_iterable))])
>
> pad(array1, array2, array3)
> for i in zip(array1, array2, array3):
> print i
>
Another option is to pad each iterator as it is exhausted. That way you
can use any iterators not just lists. e.g.
from itertools import cycle, chain
def paddedzip(*args, **kw):
padding = kw.get('padding', '')
def generate_padding():
padders = []
def padder():
if len(padders) < len(args)-1:
padders.append(None)
while 1:
yield padding
while 1:
yield padder()
return zip(*(chain(it, pad)
for (it, pad) in zip(args, generate_padding())))
for i in paddedzip(xrange(10), ['one', 'two', 'three', 'four'],
['a', 'b', 'c'], padding='*'):
print i
More information about the Python-list
mailing list