List comprehension iterate two variables at the same time [duplicate]

戏子无情 提交于 2021-02-19 03:19:15

问题


Is it possible that with the use of list comprehension to iterate through two variables at the same time increasing the loop position in both at the same time. See example below:

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.

expected output is c = [7, 9, 11, 13, 15] (n'th element from a + n'th element from b)

Thank you.


回答1:


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]


来源:https://stackoverflow.com/questions/38269538/list-comprehension-iterate-two-variables-at-the-same-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!