繁体   English   中英

如何在 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_longestfillvalue=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.

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