Search code examples
pythonfunctional-programmingzipunzip

Zip lists of tuples


I'm doing some stuff with data from files, and I have already zipped every column with its info, but now i want to combine info from other files (where i have zipped the info too) and i don't know how to unzip and get it together.

EDIT: I have a couple of zip objects:

l1 = [('a', 'b'), ('c', 'd')] # list(zippedl1)
l2 = [('e', 'f'), ('g', 'h')] # list(zippedl1)
l3 = [('i', 'j'), ('k', 'm')] # list(zippedl1)

and i want to unzip like:

unzipped = [('a', 'c', 'e', 'g', 'i', 'k'), ('b', 'd', 'f', 'h', 'j', 'm')]

I wouldn't like to transform the zipped structures to a list, just for memory reasons. I searched and i didn't find something that helps me. Hope you can help me please!. [sorry about my bad english]


Solution

  • I believe you want to zip an unpacked chain:

    # Leaving these as zip objects as per your edit
    l1 = zip(('a', 'c'), ('b', 'd'))
    l2 = zip(('e', 'g'), ('f', 'h'))
    l3 = zip(('i', 'k'), ('j', 'm'))
    
    unzipped = [('a', 'c', 'e', 'g', 'i', 'k'), ('b', 'd', 'f', 'h', 'j', 'm')]
    

    You can simply do

    from itertools import chain
    result = list(zip(*chain(l1, l2, l3)))
    
    # You can also skip list creation if all you need to do is iterate over result:
    # for x in zip(chain(l1, l2, l3)):
    #     print(x)
    
    print(result)
    print(result == unzipped)
    

    This prints:

    [('a', 'c', 'e', 'g', 'i', 'k'), ('b', 'd', 'f', 'h', 'j', 'm')]
    True