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
  • 397
  • 5
  • 19

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,781
  • 10
  • 52
  • 75
  • This works beautifully. I stumped as to why, but I guess that means more documentation for me... – Mike Feb 02 '14 at 00:13
  • @Mike, edited with a for loop for clarity. The comprehension does what's in the for loop – mhlester Feb 02 '14 at 00:16
  • Thank you for this clarification! So if I understand correctly, the x== our "content" item (1,2 or 3) and y==our "non-content" item ('')? – Mike Feb 02 '14 at 00:18
  • Not necessarily. x loops through `[1, '', 3]` and y loops through `['', 2, '']`. The `or` picks the one you want – mhlester Feb 02 '14 at 00:20
  • 1
    `x or y or 0` is an easy fix for the zeros case. – Joel Cornett Feb 02 '14 at 00:28
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
  • 115,751
  • 26
  • 228
  • 437