将重复(循环)索引的列表元素添加到另一个列表

时间:2017-11-10 09:54:25

标签: python list

鉴于这些清单

source = [1,2,3]
additions = [1,2,3,4,5,6,7,8...]

Additions []可以是2个项目或1000个项目,source []总是3个。 如何迭代添加[]和每个项目,映射并始终将添加值添加到源值。所以在迭代中:

source[1] + additions[1]
source[2] + additions[2]
source[3] + additions[3]
source[1] + additions[4] #reset source[] here
source[2] + additions[5]
...

因此,给出示例,source []将最终为:

source = [13,17,12]

1 个答案:

答案 0 :(得分:3)

如果我已正确理解您,您可以使用itertools.cycle 循环覆盖索引。

from itertools import cycle

source = [1,2,3]
additions = [1, 2, 3, 4, 5, 6, 7, 8]

for i, j in zip(cycle(range(len(source))), additions):
     source[i] += j

print(source)
[13, 17, 12]