Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append to zip() in Python

Tags:

python

append

Given any number of zipped lists, e.g.

>>> L1 = [1,2,3]
>>> L2 = [1,2,3]
>>> zipped = zip(L1, L2)
[[(1, 1), (2, 2), (3, 3)]

how can I append another list to zipped that produces the same output as

>>> L3 = [5,5,5]
>>> zip(L1, L2, L3)
[(1, 1, 5), (2, 2, 5), (3, 3, 5)]

I was thinking in the direction of append(), but that produces the following undesired result

>>> zipped.append(L3)
[(1, 1), (2, 2), (3, 3), [5, 5, 5]]

Background: I want to create the zipped-list within a loop for any number of lists.

EDIT:

It appears to me now that I was missing one part of my problem. Here is a MWE based an Ryan's answer:

import random

N = 4
zipped2 = zip([1,2,3],[1,2,3])  # works
zipped2 = []  # does not work
for n in range(N):
    Ln = random.sample(xrange(100),3)
    zipped2 = [old + (new,) for old, new in zip(zipped2, Ln)]

print(zipped2)

Using this method on pre-zipped lists works perfectly. However, I would like to create the entire output inside the loop and thus would like to start with an empty list.

like image 765
CFW Avatar asked Dec 02 '22 12:12

CFW


1 Answers

If you really like the word zip, you can use it lots:

zip(*zip(*zipped), L3)

If you’re using Python 2 or are a fan of having people understand your code, a list comprehension is probably best:

[old + (new,) for old, new in zip(zipped, L3)]

Your edit seems to indicate you just want to zip some number of lists, though:

import random

N = 4
columns = []
for n in xrange(N):
    Ln = random.sample(xrange(100), 3)
    columns.append(Ln)

zipped2 = zip(*columns)
print(zipped2)
like image 110
Ry- Avatar answered Dec 06 '22 07:12

Ry-