2016-07-08 64 views
2

是否有可能通過使用列表理解同時遍歷兩個變量來同時增加兩個變量的循環位置。見下面的例子:列表理解同時迭代兩個變量

a = [1,2,3,4,5] 

b = [6,7,8,9,10] 

c = [i+j for i in a for j in b] # This works but the output is not what it would be expected. 

期望輸出是c = [7, 9, 11, 13, 15](從B A +第n個元件的第n個元素)

謝謝。

+2

試試這個:'c = [i + j for i,j in zip(a,b)]' – Alex

回答

2
a = [1,2,3,4,5] 
b = [6,7,8,9,10] 

c = map(sum, zip(a, b)) 
print c 

#Output 
[7, 9, 11, 13, 15]