Kevin
Kevin

Reputation: 447

Zip/Map Lists of Lists in Python

I have lists like:

L1 = [list]

L2 = [ [l1], [l2], ..., [ln] ]

I need to map these lists to

L = [ [list+l1] , [list + l2] , ..., [list + ln] ]

Right now I am just repeating L1 n times and then zipping them. Can someone please hint me to a more elegant way? In other words, I am looking to do this:

L=[]
L.append(L1 + L2[0])
L.append(L1 + L2[1])
...

It would also be nice if the solution would be robust to the following change:

L1 = [list1, list2, ..., listk]

and then L becomes

[ [list1 + list2 + ... + listk + l1] , ..., [list1 + list2 + ... + listk + ln] ]

Thanks!

Upvotes: 3

Views: 513

Answers (2)

unutbu
unutbu

Reputation: 879381

L=[]
L.append(L1 + L2[0])
L.append(L1 + L2[1])
...

is equivalent to

L = [ L1+item for item in L2 ]

If L1 = [list1, list2, ..., listk] is a list of lists, such as

In [43]: L1 = [[1,2],[2,3]]

then list1 + list2 + ... + listk can be formed with sum(L1, []):

In [44]: sum(L1,[])
Out[44]: [1, 2, 2, 3]

In [45]: [1,2]+[2,3]
Out[45]: [1, 2, 2, 3]

So in this case you could use

L1_sum = sum(L1, [])
L = [ L1_sum+item for item in L2 ]

(Aside: It is also possible to use L = [ sum(L1, [])+item for item in L2 ] but this would repeat the calculation of sum(L1, []) once for each item in L2.)

Upvotes: 4

wocoburguesa
wocoburguesa

Reputation: 748

Using list comprehensions is the pythonic way:

L = [ L1 + list for list in L2 ]

Upvotes: 2

Related Questions