简体   繁体   English

如何在没有循环的情况下在同一索引 position 中用 python 中不同大小的另一个列表的元素替换列表的元素

[英]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.我想使用 python 来执行以下操作。 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:我想用相应索引值处的list2的元素替换list1的元素,这样 output 是:

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.请注意,我无权访问 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 go - 但这并不是真正的循环 - 只是一个接一个地处理它们。

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: zip_longest将填充较短的列表 - 默认情况下,它使用None填充,但在第一次使用时,我们将 'gap' 替换为空列表,以便第二个zip_longest调用可以遍历它:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何删除2个不同列表中相同索引的元素? - How to delete elements of the same index in 2 different list? 如何拆分列表中占据相同索引位置的元素? - How to split up elements of a list that occupy the same index position? Python:如何用另一个列表中的所有元素替换列表中的元素? - Python: how to replace an element in a list with all elements from another list? Python:根据另一个列表中的元素按索引从列表中删除元素 - Python: Removing elements from list by index based on elements in another list 如何根据python中的另一个列表删除列表中的元素,没有循环? - How to remove elements in a list based on another list in python, without loops? 如何在python中将列表列表的元素与列表的另一个元素列表分发 - How to distribute elements of list of list with another elements list of list in python 如果两个元素相同,如何替换列表中的两个元素(Python) - How to replace two elements in a list if both are the same (Python) 在Python中删除具有相同索引的两个列表的元素 - Delete elements of two list with same index in python 如果 python 中的元素相同,如何交换列表中的元素? - How to swap the elements in a list if elements are same in python? 如何随机替换列表元素与另一个列表元素? - How to randomly replace elements of list with another list elements?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM