我创建了两个列表。
list1 = [1, 2, 3, 4, 5, 6]
list2 = [1, 2, 3, 4, 5, 6]
创建两个列表后,我想要添加list1和list2的元素。 list1的每个元素都应该添加到list2的每个元素。
我只能将两个列表合并在一起:
list1[:] + lis2[:]
我查找了蟒蛇教程,但找不到任何东西。
我如何才能在python中添加两个列表项的元素呢?
编辑1:好的,我已经遇到了被标记为重复的问题,但我的问题不同。
我希望list1的每个元素都应该添加到list2的每个元素中。例如:
list1[1] + list2[1] adds and gives 2 and
list1[1] + list2[2] adds and gives 3 so on...
新列表应该包含36个元素
答案 0 :(得分:1)
您可以使用list comprehension和zip
(或itertools.izip
作为大型列表):
>>> list1 = [1, 2, 3, 4, 5, 6]
>>> list2 = [1, 2, 3, 4, 5, 6]
>>> [x+y for x,y in zip(list1, list2)]
[2, 4, 6, 8, 10, 12]
>>>
答案 1 :(得分:1)
>>> list1 = [1, 2, 3, 4, 5, 6]
>>> list2 = [1, 2, 3, 4, 5, 6]
然后
>>> import operator
>>> map(operator.add, list1, list2)
[2, 4, 6, 8, 10, 12]
和
>>> [x+y for x in list1 for y in list2]
[2, 3, 4, 5, 6, 7, 3, 4, 5, 6, 7, 8, 4, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 10, 6, 7, 8, 9, 10, 11, 7, 8, 9, 10, 11, 12]
>>> len([x+y for x in list1 for y in list2])
36
答案 2 :(得分:1)
尝试使用list comprehensions:
[e1 + e2 for e1, e2 in zip(list1, list2)]
答案 3 :(得分:1)
print [i+ j for i in list1 for j in list2]
我想......如果我理解这个问题的话吗?
如果你有
list1 = [1, 2, 3, 4, 5, 6]
list2 = [1, 2, 3, 4, 5, 6]
然后这将导致
[ 2,3,4,5,6,7, 3,4,5,6,7,8, 4,5,6,7,8,9, 5,6,7,8,9,10, 6,7,8,9,10,11, 7,8,9,10,11,12]
听起来像你想要的
或以酷炫的方式做到这一点
from itertools import chain
l2 = numpy.array(list2)
print chain(*[l2+i for i in list1])
答案 4 :(得分:1)
获取两个列表并生成元素配对的过程是2x2 Cartesian Product
获得2x2笛卡儿产品后,将操作员应用于您希望的配对;在这种情况下sum
。
Python itertools有product:
>>> import itertools as it
>>> list(it.product('xyz','123'))
[('x', '1'), ('x', '2'), ('x', '3'), ('y', '1'), ('y', '2'), ('y', '3'), ('z', '1'), ('z', '2'), ('z', '3')]
然后,您可以使用imap来应用sum
功能:
>>> list(it.imap(sum, it.product(list1, list2)))
[2, 3, 4, 5, 6, 7, 3, 4, 5, 6, 7, 8, 4, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 10, 6, 7, 8, 9, 10, 11, 7, 8, 9, 10, 11, 12]
Itertools将支持产品内部的任意数量的列表(即多维笛卡尔积):
>>> list(it.imap(sum, it.product([1,2,3],[3,4,5],[6,7,8],[9,10,11])))
[19, 20, 21, 20, 21, 22, 21, 22, 23, 20, 21, 22, 21, 22, 23, 22, 23, 24, 21, 22, 23, 22, 23, 24, 23, 24, 25, 20, 21, 22, 21, 22, 23, 22, 23, 24, 21, 22, 23, 22, 23, 24, 23, 24, 25, 22, 23, 24, 23, 24, 25, 24, 25, 26, 21, 22, 23, 22, 23, 24, 23, 24, 25, 22, 23, 24, 23, 24, 25, 24, 25, 26, 23, 24, 25, 24, 25, 26, 25, 26, 27]
并且在此过程中不会产生一堆扔掉的名单。