python - Merge fixed length multiple lists -
how merge fixed length multiple lists single list updated value in particular place. in example below, result [1,33,222,3333,11111]
.
l1 = [1, "", 111, "", 11111] l2 = ["", 22, 222, 2222, ""] l3 = ["", 33, "", 3333, ""] l4 = .... l5 = ... ....
is there inbuilt function this. can using 2 loops there must other smart ways same
you can use zip(l1, l2, l3)
, or
operator on tuples:
[tup[2] or tup[1] or tup[0] tup in zip(l1, l2, l3)]
or
operator returns first true value. , since want last true value, need apply or
operator on tuple elements in reverse.
or can zip
lists in reverse, , use or
operator in order:
[tup[0] or tup[1] or tup[2] tup in zip(l3, l2, l1)]
update:
instead of variable number of list, suggest have list of list
instead. in case can result this:
li = [[1, "", 111, "", 11111], ["", 22, 222, 2222, ""], ["", 33, "", 3333, ""], ..... on ] print [reduce(lambda a, b: or b, tup) tup in zip(*li[::-1])]
Comments
Post a Comment