繁体   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

我想使用 python 来执行以下操作。 假设我有两个列表列表:

list1 = [[0,0,0], 
         [0,0,0], 
         [0,0,0]]

list2 = [[ 1, "b"], 
         ["a", 4 ]]

我想用相应索引值处的list2的元素替换list1的元素,这样 output 是:

output = [[  1,"b", 0], 
          ["a",  4, 0], 
          [  0,  0, 0]]

有没有一种快速的方法来代替使用循环? 计算时间是我需要这个的关键。 请注意,我无权访问 pandas。 谢谢

您将需要依次通过每个嵌套列表使用for go - 但这并不是真正的循环 - 只是一个接一个地处理它们。

对于每个内部列表,如果它们存在/为真,您可以使用以下内容始终选择第二个列表中的元素。 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.

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