[Tutor] smarter way of looping
Kent Johnson
kent37 at tds.net
Thu Jan 26 14:48:51 CET 2006
Elderely Geek wrote:
> Hi,
> I`m a python newbie and could use some help.
>
> I often do a loop over arbitrary number of sequences. I do it like this:
>
> for elem1 in seq1:
> for elem2 in seq2:
> do whatever seq1,seq2
>
> this isn`t nice I think. Is there some way I can say
> myiterator=geniousfunction(seq1,seq2,seq3)
>
> and then myiterator.next() and have it return the corresponding elemnts
> from all sequences like if
>
> seq1 = ['a','b']
> seq2 = [1,2]
>
> I could get
>
> a 1
> a 2
> b 1
> b 2
This is a perennial topic on comp.lang.python and there are many clever
ways to do it. The most straightforward way is to use a recursive
generator. The idea is, at each step, combine each element of the first
sequence with each sequence generated from the remaining sequences. Here
is one way to do it:
def combine(*seqs):
if not seqs:
yield []
else:
for item in seqs[0]:
for subitem in combine(*seqs[1:]):
yield [item] + subitem
seq1 = ['a','b']
seq2 = [1,2]
for seq in combine(seq1, seq2):
print seq
print list(combine(seq1, seq2))
This uses some fairly advanced bits of Python:
arbitrary argument lists (I can't find a good doc for this)
generators: http://www.python.org/doc/2.3.5/whatsnew/section-generators.html
and recursion.
>
> also, how do you loop over all the elements that can be returned by
> myiterator?
As in the example above, you can iterate it with a for loop, or convert
to a list.
Kent
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list