简体   繁体   English

将两个不同长度列表的元素相加成一个新列表

[英]Sum elements of two lists of different lengths into a new one

I'm trying to learn python and i'm doing some basic exercises like this one.我正在尝试学习 python 并且我正在做一些像这样的基本练习。 I've tried using list comprehension, but the newly created list has only the sum of the first two elements.我试过使用列表推导,但新创建的列表只有前两个元素的总和。 How can i put the remaining integers of L1 in L3 using list comprehension?如何使用列表理解将 L1 的剩余整数放入 L3 中?

L1 = [3, 7, 1, 54]
L2 = [0, 128]
L3 = [x+y for x,y in zip(L1, L2)]
for i in L3:
    print(i, end= " ")

One way to make your code work is to extend the array L2 to the length of L1, eg to fill it with zeros:使您的代码工作的一种方法是将数组 L2 扩展到 L1 的长度,例如用零填充它:

L1 = [3, 7, 1, 54]
L2 = [0, 128]

# extend the L2 array by the difference in length of both arrays.
L2.extend([0] * (len(L1) - len(L2)))

L3 = [x+y for x,y in zip(L1, L2)]
for i in L3:
    print(i, end= " ")

Another apporach is to use itertools.zip_longest , see this answer .另一种方法是使用itertools.zip_longest ,请参阅此答案

Below code will work.下面的代码将起作用。

import itertools


def add_data(list1, list2):
    temp_list= list(itertools.zip_longest(list1, list2, fillvalue= 0))
    return [x+y for x,y in temp_list]


if __name__ == '__main__':
    l3= add_data([3, 7, 1, 54],[0, 128])
    print(l3)

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

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