>>> a = [1,2,3,4]
>>> b = [17,12,11,10]
>>> c = [-1,-4,5,9]
>>> list(map(lambda x,y,z:x+y+z, a,b,c))
[17, 10, 19, 23]
尝试:
>>>[(x+y+z) for x in a for y in b for z in c]
但是添加了这些列表中每个可能的元素组合(不仅仅是第一个,第二个和第二个等):
[17, 14, 23, 27, 12, 9, 18, 22, 11, 8, 17, 21, 10, 7, 16, 20, 18, 15, 24, 28, 13, 10, 19, 23, 12, 9, 18, 22, 11, 8, 17, 21, 19, 16, 25, 29, 14, 11, 20, 24, 13, 10, 19, 23, 12, 9, 18, 22, 20, 17, 26, 30, 15, 12, 21, 25, 14, 11, 20, 24, 13, 10, 19, 23]
这有可能吗?感谢。
答案 0 :(得分:5)
你正在寻找zip
,它在锁定步骤中驱动多个迭代':
[x+y+z for x, y, z in zip(a, b, c)]
您的原始尝试产生三个列表中的Cartesian product。 itertools
模块中存在a helper function笛卡尔积。
答案 1 :(得分:1)
一种可能性:
In [36]:
[ a[i] + b[i] + c[i] for i in range(len(a))]
Out[36]:
[17, 10, 19, 23]
这假设所有列表的长度相同
答案 2 :(得分:1)
一种简单的方法是:
answerList = []
for key,value in enumerate(a):
answerList.append(a[key]+b[key]+c[key])