简体   繁体   English

如何在 Python 中将一个列表中的整数添加到另一个列表中

[英]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_longestfillvalue=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.

相关问题 如何将一个列表中的所有整数添加到另一个列表中的整数,并在Python中以相同的顺序使用不同的长度? - How do I add all integers in one list to integers on another list with different length in the same order in Python? 如何在python中将一个列表添加到另一个列表? - how to ADD a one list to another in python? 如何将数字添加到列表中的所有整数(python) - How to add number to all integers in list (python) Python - 如何添加整数(可能在列表中?) - Python - how to add integers (possibly in a list?) 如何将整数列表加入一个整数python - How to join list of integers into one integer python 如何在Python3中将元素从一个列表添加到另一个列表? - How to add the elements from one list to another list in Python3? 将一个列表中的字符串与另一个列表中的整数“配对”的最简单方法是什么(在python中)? - What is the easiest way “pair” strings in one list with integers in another (in python)? Python,如何将元素从一个列表随机添加/追加到另一个列表? - Python, how to randomly add/append elements from one list to another? 如何将元素从一个类添加到另一个类列表,python - How to add elements from one class to another class list, python 如何从一个列表中删除某些内容并将其添加到 python 中的另一个列表中 - How to remove something from one list and add it to another in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM