1

I'm a bit new to python's data structure tricks, and I've been struggling with a simple problem.

I have 2 2d lists

L1=[[1, '', 3],[1, '', 3]...]
L2=[['',2,''],['',2,''].....]

I'm looking for a simple way to merge the two lists such that the result is a new 2d list in the form:

result=[[1,2,3],[1,2,3]....]

I've tried

newestlist=[sum(x,[]) for x in zip(mylist, mylist2)]

but it yields the result

badresult=[[1,'',3,'',2,'']....]

is there a way way to accomplish this?

Mike
  • 357
  • 5
  • 17

2 Answers2

3

This doesn't work if any numbers are 0:

>>> [[x or y or 0 for x, y in zip(a, b)] for a, b in zip(L1, L2)]
[[1, 2, 3], [1, 2, 3]]

Edit: Breaking the comprehension into a for loop for clarity:

output = []
for a, b in zip(L1, L2):
    innerlist = []
    for x, y in zip(a, b):
        innerlist.append(x or y or 0)  # 1 or '' = 1; '' or 2 = 2; etc
    output.append(innerlist)
mhlester
  • 22,072
  • 10
  • 50
  • 74
1

You could try:

newestlist = [[a if a != "" else b for a, b in zip(l1, l2)]
              for l1, l2 in zip(L1, L2)]

This gives me your desired output:

[[1, 2, 3], [1, 2, 3]]
jonrsharpe
  • 107,083
  • 22
  • 201
  • 376