On Apr 21, 4:42 pm, Matimus <[EMAIL PROTECTED]> wrote: > On Apr 21, 12:05 pm, <[EMAIL PROTECTED]> 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 -- http://mail.python.org/mailman/listinfo/python-list