ListA = [1,2,3]
ListB = [10,20,30]
我想将列表的内容加在一起(1+10,2+20,3+30)
,创建以下列表:
ListC = [11,22,33]
是否有以这种方式专门合并列表的函数?
答案 0 :(得分:9)
这有效:
>>> ListA = [1,2,3]
>>> ListB = [10,20,30]
>>> list(map(sum, zip(ListA, ListB)))
[11, 22, 33]
>>>
上面使用的所有内置函数都解释为here。
另一种解决方案是使用list comprehension。
根据您的口味,您可以这样做:
>>> [sum(x) for x in zip(ListA, ListB)]
[11, 22, 33]
>>>
或者这个:
>>> [x+y for x,y in zip(ListA, ListB)]
[11, 22, 33]
>>>