Code question

Matimus mccredie at gmail.com
Mon Apr 21 19:59:30 EDT 2008


On Apr 21, 4:16 pm, George Sakkis <george.sak... at gmail.com> wrote:
> On Apr 21, 4:42 pm, Matimus <mccre... at gmail.com> wrote:
>
>
>
> > On Apr 21, 12:05 pm, <jyoun... at kc.rr.com> wrote:
>
> > > I've been trying to figure out a way to combine lists similar to how zip() works.  The main
> > > difference though is I want to work with different length lists and combine them.  I came up with
> > > the example below, which returns a list like I'm wanting.  I'm assuming it's somewhat efficient
> > > (although I wonder if the lists were huge that the 'if' statement might slow things down?).
>
> > > If anyone has time, I was wondering if you could share your thoughts on whether this is an
> > > efficient way to do something like this, if it's horrible and slow, etc.
>
> > > Thanks!
>
> > > Jay
>
> > > # ----------------------------
>
> > > def combineLists(theLists):
> > >     cntList = len(theLists)
> > >     lenList = [len(x) for x in theLists]
>
> > >     maxList = max(lenList)
>
> > >     combinedList = []
>
> > >     for x in range(maxList):
> > >         for n in range(cntList):
> > >             if lenList[n] > x: combinedList.append(theLists[n][x])
>
> > >     print combinedList
>
> > > combineLists([a, b, c])
>
> > > # ----------------------------
>
> > > # --> ['a', '1', 'a1', 'b', '2', 'b2', 'c', 'c3', 'd4', 'e5']
>
> > I would probably do something like this:
>
> > >>> def combine(*seqs):
>
> > ...    seqs = [iter(s) for s in seqs]
> > ...    while seqs:
> > ...       for g in seqs:
> > ...          try:
> > ...             yield g.next()
> > ...          except StopIteration:
> > ...             seqs.remove(g)
> > ...>>> a = 'abc'
> > >>> b = '12'
> > >>> c = 'a1 b2 c3 d4 e5'.split()
> > >>> list(combine(a,b,c))
>
> > ['a', '1', 'a1', 'b', '2', 'b2', 'c', 'c3', 'd4', 'e5']
>
> > It has the advantage that it uses the generator protocol, so you can
> > pass in any type of sequence. It uses arbitrary arguments to make its
> > use closer to that of zip. It is also a generator, so it takes
> > advantage of lazy evaluation. Notice that there is never any checking
> > of length.
>
> > Matt
>
> A similar solution using the itertools module:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/528936
>
> George

Very nice. I was wondering if there would be a way to pull that try/
except block outside of the for loop. Jay: use this solution. It has
all of the advantages I list for my solution, only it should be
faster, and lazier.

Matt



More information about the Python-list mailing list