Ad

How To Make A 2D List With Every Element(list) Is Created By Union Of Two Other Lists?

- 1 answer

I have two lists:

D1=[["a "," "," "," "," "," "],["b "," ","o"," "," "," "],["c ","x"," "," "," "," "],["d "," "," "," "," "," "],["e "," "," "," "," "," "]]

D2=[["a "," ","o"," ","x"," "],
["b "," "," "," "," "," "],["c "," "," "," "," "," "],["d "," "," "," "," "," "],["e "," "," "," "," "," "]]

D=[]

I want to make a list D so,D[i]=D1[i] + D2[i],for example the first element(list) looks like this:

D=[["a "," "," "," "," "," ","a "," ","o"," ","x"," "],...]

Please help me I am new in python

Ad

Answer

Try this:

D = [i+j for i,j in zip(D1,D2)]

if lengths are different it will cut the rest and go forward to the minimum of D1, D2. if you want the opposite, use zip_longest, like this:

from itertools import zip_longest

D = [i+j for i,j in zip_longest(D1,D2)]

But both will work if D1 and D2 have the same length.

Ad
source: stackoverflow.com
Ad