Loop in a loop?

A

Arnaud Delobelle

Instead of counting the exceptions, we can limit the padding iterables
by using an iterator that returns len(iterables) - 1 padding
generators, use a sort of lazy chain, and then just izip.

from itertools import izip, repeat

def chain_next(xs, yg):
    for x in xs: yield x
    for y in yg.next(): yield y

def izippad(*xs, **kw):
    padder = repeat(kw.get('padding', None))
    padder_gen = repeat(padder, len(xs) - 1)
    return izip(*[chain_next(x, padder_gen) for x in xs])

I have had the need for such a 'padded zip' before and my
implementation was eerily similar:

from itertools import repeat, chain, izip

def repeatnext(iterator):
val = iterator.next()
while True: yield val

def longzip(default, *iterables):
defaultgen = repeat(default, len(iterables) - 1)
return izip(*[chain(it, repeatnext(defaultgen)) for it in
iterables])
 
B

Bruno Desthuilliers

Roel Schroeven a écrit :
Sacred Heart schreef:

One solution is with map() instead if zip(). map() with None as the
first argument works much like zip(), but it keeps looping if one of the
lists is exhausted. When that happens, it uses None for those values:

Yek ! Should have read the doc more carefully. Height years of Python,
and I didn't knew this one :(
 
B

Bruno Desthuilliers

Paul Rubin a écrit :
Not trying to pick on you personally but there's this disease
when a newbie comes with a basically simple question (in this case,
how to solve the problem with ordinary lists) and gets back a lot
of complex, overly general "graduate level" solutions.

As far as I'm concerned, it's certainly a GoodThing(tm) - everyone
learns in the process.
 
S

Sacred Heart

Sacred Heart said:
array1 = ['one','two','three','four']
array2 = ['a','b','c','d']
I want to loop through array1 and add elements from array2 at the end,
so it looks like this:
one a
two b
three c
four c

The "functional" style is to use the zip function that someone
described. The old-fashioned way is simply:

n = len(array1)
for i in xrange(n):
print array1, array2

You can modify this in various ways if the lengths of the lists are
not equal. E.g.


Thank you Paul, and everybody else contributing with answers of
various complexity. Although a whole bunch of them was way too complex
for my simple problem, but that's ok.

I now know how to use map and zip, and also learned some tips and
tricks.

Thanks.

All the best,
SH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
474,161
Messages
2,570,892
Members
47,427
Latest member
HildredDic

Latest Threads

Top