Home > Net >  how to sum up elements in list of lists for arbitrary combination in python
how to sum up elements in list of lists for arbitrary combination in python

Time:10-20

I have a list like this,

 A =      [[0.8922063, 0.26672425],
          [0.34475611, 0.35976697],
          [0.33253499, 0.18923898],
          [0.66872466, 0.46248986],
          [0.72823733, 0.10537784],
          [0.40903598, 0.70639412],
          [0.79926596, 0.90095583],
          [0.67886544, 0.84573289],
          [0.3641813, 0.64296743],
          [0.07461196, 0.74290527]]

which is the combination of lists of list

and I have another list

p = [5,4,2]

I need to sum up elements of list A corresponding to P, i.e, the sum of the first 5 sub-list of A, then the sum of the next 4 (6th to 9th) sub-list and finally the sum of the last 2 sub-list.

CodePudding user response:

Transform your list p into a list of the slices you want:

>>> q = [0,5,9,10]

You can do that this way:

>>> q = [sum(p[:i]) for i in range(len(p) 1)]

Then sum the slices of A:

>>> for i in range(len(q)-1):
        listn = sum(sum(x) for x in A[q[i]:q[i 1]])
        print(listn)

4.35005729
5.34739895
0.81751723

CodePudding user response:

This function returns a list of sums from chunks in A by keeping track of our last sliced element (starting at 0) and incrementing the index to slice with the numbers in p.

def sum_sublists(list1 : list, list2 : list) -> list:
    sums=[]
    last_slice = 0
    for chunk_size in list2:
        next_slice = last_slice chunk_size
        sums.append(sum([sum(el) for el in list1[last_slice:next_slice]]))
        last_slice = next_slice
    return sums

if __name__ == '__main__':
    p = [5,4,1]
    A = [[0.8922063, 0.26672425],
        [0.34475611, 0.35976697],
        [0.33253499, 0.18923898],
        [0.66872466, 0.46248986],
        [0.72823733, 0.10537784],

        [0.40903598, 0.70639412],
        [0.79926596, 0.90095583],
        [0.67886544, 0.84573289],
        [0.3641813, 0.64296743],
        
        [0.07461196, 0.74290527],   
        ]

    print(sum_sublists(A, p))
  • Related