[英]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.