Reputation: 89
I want to use python to do the following. Let's say I have two list of lists:
list1 = [[0,0,0],
[0,0,0],
[0,0,0]]
list2 = [[ 1, "b"],
["a", 4 ]]
And I want to replace the elements of list1
with the elements of list2
at the corresponding index value such that the output is:
output = [[ 1,"b", 0],
["a", 4, 0],
[ 0, 0, 0]]
Is there a quick way of doing this instead of using a loop? Computational time is key for what I need this for. Please note I do not have access to pandas. Thanks
Upvotes: 0
Views: 372
Reputation: 11060
You will need to use for
to go through each of the nested lists in turn - however this isn't really a loop - just processing them one after another.
For each inner list, you can use the following to always pick the elements in the second list if they exist/are true. zip_longest
will pad the shorter list - by default it pads with None
but for the first use we replace the 'gap' with an empty list so that the second zip_longest
call can iterate over it:
from itertools import zip_longest
list1 = [[0,0,0],
[0,0,0],
[0,0,0]]
list2 = [[ 1, "b"],
["a", 4 ]]
new_list = []
for l1, l2 in zip_longest(list1, list2, fillvalue=[]):
new_list.append([y if y else x for x, y in zip_longest(l1, l2)])
print(new_list)
Upvotes: 2