基于索引列表对列表元素求和

时间:2017-07-20 05:38:17

标签: python list

我怎么能得到结果和abResult?请指导我,我真的很感激!

x=[1,2]      

y=[3,4,5]

result= [3,9]   <===  the sum of result determine by x

============= OR ==========

a=[1,3,2]

b= [4,2,3,4,5,10]

abResult= [4,9,15]

2 个答案:

答案 0 :(得分:2)

a=[1,3,2]

b= [4,2,3,4,5,10]

res=[]

for i in a:
    res.append(sum(b[:i]))
    b=b[i:]

res存储您的结果

答案 1 :(得分:-1)

它可能工作正常。

def isValid(counter, array): # valid if sum of counter equals array length
    return sum(counter) == len(array)

def calc(counter, array):
    if not isValid(counter, array):
        return []
    flag = 0
    for x in counter:
        yield sum(array[flag:flag+x]) # sum between (flag ~ flag+x)
        flag += x                     # add x to flag for next flag