Home > Enterprise >  How to consolidate the function of local_sum (list of mixed numbers and sublists) in one loop?
How to consolidate the function of local_sum (list of mixed numbers and sublists) in one loop?

Time:07-25

Given a list containing numbers, and sublists. The goal of this function - local_sum() is to get all local sum (or range sum) with these conditions: 1) if it's a sublist, get its sum and remain a list, if consecutive numbers just add up them.

[Notes] a local variable just what's needed - enables keeping the running sum of sublists. Thanks.

Examples of in/outputs shown as following:

from itertools import groupby

A =   [3, 4, 2, [10, 22, 32, 14], 9, 8, 6, [22, 11]]
expected = [9, 23,  [111]   
ans = [9, [78], 23, [33]]   <----   currently getting

# is there a way to get this expected result in one shot, instead of doing another processing? 

# my current working code:
def local_sum(L):
    '''add up the numbers which are not in sublist,
       and sum the sublist as a one unit, if there're more than one -
       try to consolidate it into ONE.
    '''
    ans = []
    
    for k, g in groupby(L, key=lambda x: isinstance(x, list)):
        
        if k:                         # the group is a list
                                      # the whole list :: sum(list(g))X
            ans.append([sum(*g)])     # g is _grouper instance
            
        else:
            
            ans.append(sum(list(g)))           # each single number
    
    return ans

CodePudding user response:

With only one example, it seems you want to keep a running total of everything in a sublist:

from itertools import groupby

A = [3, 4, 2, [10, 22, 32, 14], 9, 8, 6, [22, 11]]

def local_sum(L):
    ans = []
    sub = 0
    for k, g in groupby(A, key=lambda x: isinstance(x, list)):
        if k:
            sub  = sum(*g)
        else:
            ans.append(sum(list(g)))
    ans.append([sub])
    return ans

print(local_sum(A))

Output:

[9, 23, [111]]

CodePudding user response:

Alternatively:

int_=0
int_list = []
for x in A:
    if isinstance(x, int):
        int_ =x
    else:
        int_list.append(int_)
        int_=0
oneliner = [sum(map(lambda x: sum(x), filter(lambda x: isinstance(x, list), A)))]
int_list.append(oneliner)

Gives:

[9, 23, [111]]
  • Related