简体   繁体   中英

How to replace elements of a list with elements of another list of a different size in python in the same index position without a loop

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM