![](/img/trans.png)
[英]How do I add all integers in one list to integers on another list with different length in the same order in Python?
[英]How to add the integers in one list to another in Python
我有两个使用 python 的列表,比如说:
lst = [1, 1, 2]
lst2 = [1, 1]
我试图用lst2
“添加” lst
的元素,这样我得到: [2, 2, 2]
我试过做:
lst + lst2
这只会让我[1, 1, 2, 1, 1,]
任何帮助将非常感激!
也许这个?
>>> import itertools
>>> [sum(pair) for pair in itertools.zip_longest(lst, lst2, fillvalue=0)]
[2, 2, 2]
您可以将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)
印刷:
[2, 2, 2]
如果您更喜欢不使用迭代器:
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.