[Tutor] smarter way of looping
Elderly Geek
epost2 at gmail.com
Thu Jan 26 16:00:13 CET 2006
On 1/26/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
> > 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.
>
> Actually its pretty common and not that ugly.
> But...
Ok, I see. I was trying to show that I`m (was) unable to pass in an
arbitrary number of secuences, but the generator in one of the other
posts in thread solves this, right? quite impressive that one I think
> > myiterator=geniousfunction(seq1,seq2,seq3)
> >
> > and then myiterator.next() and have it return the corresponding elemnts
> > from all sequences
>
> The problem is that there are so many different ways you can do that.
> Python offers several options but none of them solve all the cases.
>
> Look at the documentation for
>
> List Comprehensions
> zip()
> map()
> filter()
> reduce()
I will. Thanks.
>
> > seq1 = ['a','b']
> > seq2 = [1,2]
> > a 1
> > a 2
> > b 1
> > b 2
>
> [a,b for a in seq1 for b in seq2]
>
> > how do you loop over all the elements that can be returned by
> > myiterator?
>
> return the options as a list of tuples and then use the usual list iteration
> techniques.
>
> for elem in [a,b for a in seq1 for b in seq2]:
> # use elem here
>
that`s nice. Thanks for the replies
More information about the Tutor
mailing list