[英]How to add the integers in one list to another in Python
I have two lists using python, let's say:我有两个使用 python 的列表,比如说:
lst = [1, 1, 2]
lst2 = [1, 1]
And I'm trying to "add" the elemtents of lst
with lst2
such that I get: [2, 2, 2]
我试图用
lst2
“添加” lst
的元素,这样我得到: [2, 2, 2]
I have tried doing:我试过做:
lst + lst2
This only get's me [1, 1, 2, 1, 1,]
这只会让我
[1, 1, 2, 1, 1,]
Any help would be much appreciated!任何帮助将非常感激!
Maybe this?也许这个?
>>> import itertools
>>> [sum(pair) for pair in itertools.zip_longest(lst, lst2, fillvalue=0)]
[2, 2, 2]
You can use itertools.zip_longest
with fillvalue=0
:您可以将
itertools.zip_longest
与fillvalue=0
一起使用:
from itertools import zip_longest
lst = [a + b for a, b in zip_longest(lst, lst2, fillvalue=0)]
print(lst)
Prints:印刷:
[2, 2, 2]
if you prefer to do it without iterator:如果您更喜欢不使用迭代器:
lst3 = [lst[i]+lst2[i] for i in range(min(len(lst), len(lst2)))]+lst[min(len(lst), len(lst2)):]+lst2[min(len(lst), len(lst2)):]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.