如何将列表中的每个数字添加到数字?

时间:2016-03-24 11:10:42

标签: python

这些是我的清单。如何将list1中的每个号码添加到list2中的每个号码?

list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]
outcomelist = [7,8,9,10,11,8,9,11,12,9,10,11,12,13,10,11,12,13,14,1,12,13,14,15]

4 个答案:

答案 0 :(得分:1)

使用zip内置功能和list comprehension

[x + y for x, y in zip([1,2,3,4,5], [6,7,8,9,10])]

>>> [7, 9, 11, 13, 15]

如果你想要总结所有人,请不要zipping

[x + y for x in [1,2,3,4,5] for y in [6,7,8,9,10]]

>>> [7, 8, 9, 10, 11, 8, 9, 10, 11, 12, 9, 10, 11, 12, 13, 10, 11, 12, 13, 14, 11, 12, 13, 14, 15]

答案 1 :(得分:1)

如果要构建新列表,可以执行以下操作:

for idx, tuple in enumerate(zip(list1, list2)):
    list2[idx] = tuple[1] + tuple[0]

如果你想要更新list2,你可以使用enumerate来访问索引并更新列表:

{{1}}

答案 2 :(得分:0)

python3

add=lambda x,y:x+y
list(map(add,list1,list2))#[7, 9, 11, 13, 15]

import operator
list(map(operator.add,list1,list2))#[7, 9, 11, 13, 15]

list comperhension:

[x+y for x,y in zip(list1,list2)]#[7, 9, 11, 13, 15]
[sum([x,y]) for x,y in zip(list1,list2)]#[7, 9, 11, 13, 15]

答案 3 :(得分:0)

使用itertools.product制作所有可能的对:

>>> import itertools
>>> list1 = [1,2,3,4,5]
>>> list2 = [6,7,8,9,10]
>>> [x + y for (x,y) in itertools.product(list1, list2)]
>>> resultlist
[7, 8, 9, 10, 11, 8, 9, 10, 11, 12, 9, 10, 11, 12, 13, 10, 11, 12, 13, 14, 11, 12, 13, 14, 15]

您可以将其扩展到多个列表:

>>> list1 = [1,2,3]
>>> list2 = [4,5,6]
>>> list3 = [7,8,9]
>>> [x + y + z for (x, y, z) in itertools.product(list1, list2, list3)]

甚至可变数量的列表:

>>> [sum(items) for items in itertools.products(*list_of_lists)]