Python-合并两个同时连接的列表 [英] Python - Merge two lists with a simultaneous concatenation

查看:112
本文介绍了Python-合并两个同时连接的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ListA = [1,2,3]
ListB = [10,20,30]

我想将列表的内容加在一起(1+10,2+20,3+30)创建以下列表:

ListC = [11,22,33]

是否存在专门以这种方式合并列表的功能?

解决方案

这有效:

>>> ListA = [1,2,3]
>>> ListB = [10,20,30]
>>> list(map(sum, zip(ListA, ListB)))
[11, 22, 33]
>>>

此处中说明了上面使用的所有内置函数. /p>


另一种解决方案是使用列表理解 .

根据您的口味,您可以这样做:

>>> [sum(x) for x in zip(ListA, ListB)]
[11, 22, 33]
>>>

或者这个:

>>> [x+y for x,y in zip(ListA, ListB)]
[11, 22, 33]
>>>

ListA = [1,2,3]
ListB = [10,20,30]

I want to add the contents of the lists together (1+10,2+20,3+30) creating the following list:

ListC = [11,22,33]

Is there a function that merges lists specifically in this manner?

解决方案

This works:

>>> ListA = [1,2,3]
>>> ListB = [10,20,30]
>>> list(map(sum, zip(ListA, ListB)))
[11, 22, 33]
>>>

All of the built-ins used above are explained here.


Another solution would be to use a list comprehension.

Depending on your taste, you could do this:

>>> [sum(x) for x in zip(ListA, ListB)]
[11, 22, 33]
>>>

or this:

>>> [x+y for x,y in zip(ListA, ListB)]
[11, 22, 33]
>>>

这篇关于Python-合并两个同时连接的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆