关于迭代有很多答案,但是我没有找到想要的东西。 因此,情况如下: 我有2个2种不同长度的清单。但是l1只能是<= l2
l1 = [2, 3, 1, 2, 2]
l2 = [12, 4, 5, 2, 9, 33, 5, 8, 4, 5, 1, 7, 3]
l3 = []
我想写一个返回的函数:
l3 = [(l2[0] + l2[1], l2[2] + l2[3] + l2[4], l2[5], l3[6] + l3[7]...)]
所以
if l1[0] == 2:
Add the value of the sum of (the 2 first values of l2) in l3
if l1[0] == 3:
Add the value of the sum of (the next 3 values of l2) in l3
我尝试过:
i = 0
for v in l1:
for k in l2:
sum(l2[i])
i += 1
但是,是行不通的。 谢谢 !
答案 0 :(得分:0)
l1 = [2, 3, 1, 2, 2]
l2 = [12, 4, 5, 2, 9, 33, 5, 8, 4, 5, 1, 7, 3]
l3 = []
assert (len(l2) >= sum(l1))
i = 0
for e in l1:
l3.append(sum(l2[i:i+e]))
i += e
print (l3)
# [16, 16, 33, 13, 9]