Code question

jyoung79 at kc.rr.com jyoung79 at kc.rr.com
Mon Apr 21 15:05:12 EDT 2008


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

# ----------------------------

a = ['a', 'b', 'c']
b = ['1', '2']
c = ['a1', 'b2', 'c3', 'd4', 'e5']

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']





More information about the Python-list mailing list