learner
learner

Reputation: 2742

Merge fixed length multiple lists

How to merge fixed length multiple lists together to get a single list with the most updated value in a particular place. In example below, the result would be [1,33,222,3333,11111].

l1 = [1,    "", 111,    "", 11111]
l2 = ["",   22, 222,    2222,   ""]
l3 = ["",   33, "", 3333,   ""]
l4 = ....
l5 = ...
....

Is there any inbuilt function to do this. I can do it using two loops but there must be some other smart ways to do the same

Upvotes: 1

Views: 85

Answers (2)

Stuart
Stuart

Reputation: 9858

An alternative way is using map and a function to get the first non-blank item in a series of arguments:

def first_nonblank(*args):
    for item in args:
        if item is not '':
            return item

print map(first_nonblank, l3, l2, l1)

or

print map(first_nonblank, *li[::-1])

if li is a list of lists as in @Rohit Jain's answer.

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213223

You can use zip(l1, l2, l3) and then or operator on tuples:

[tup[2] or tup[1] or tup[0] for tup in zip(l1, l2, l3)]

or operator returns the first true value. And since you want the last true value, so you need to apply or operator on tuple elements in reverse.

Or you can zip the lists in reverse, and use or operator in order:

[tup[0] or tup[1] or tup[2] for tup in zip(l3, l2, l1)]

Update:

Instead of variable number of list, I would suggest you to have a list of list instead. In that case you can get the result like this:

li = [[1,    "", 111,    "", 11111], 
      ["",   22, 222,    2222,   ""], 
      ["",   33, "", 3333,   ""], ..... so on
     ]

print [reduce(lambda a, b: a or b, tup) for tup in zip(*li[::-1])]

Upvotes: 5

Related Questions