Skip to content Skip to sidebar Skip to footer

Merging Two Lists, Removing Empty Strings

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

Solution 1:

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)

Solution 2:

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]]

Post a Comment for "Merging Two Lists, Removing Empty Strings"