user10886646
user10886646

Reputation:

nested list of lists of inegers - doing arithmetic operation

I have a list like below and need to firs add items in each list and then multiply all results 2+4 = 6 , 3+ (-2)=1, 2+3+2=7, -7+1=-6 then 6*1*7*(-6) = -252 I know how to do it by accessing indexes and it works (as below) but I also need to do it in a way that it will work no matter how many sublist there is

nested_lst = [[2,4], [3,-2],[2,3,2], [-7,1]]
a= nested_lst[0][0] + nested_lst[0][1]
b= nested_lst[1][0] + nested_lst[1][1]
c= nested_lst[2][0] + nested_lst[2][1] + nested_lst[2][2]
d= nested_lst[3][0] + nested_lst[3][1]

def sum_then_product(list):
    multip= a*b*c*d
    return multip
print sum_then_product(nested_lst)

I have tried with for loop which gives me addition but I don't know how to perform here multiplication. I am new to it. Please, help

nested_lst = [[2,4], [3,-2],[2,3,2], [-7,1]]
for i in nested_lst:
    print sum(i)

Upvotes: 2

Views: 29

Answers (1)

Niels Henkens
Niels Henkens

Reputation: 2696

Is this what you are looking for?

nested_lst = [[2,4], [3,-2],[2,3,2], [-7,1]] # your list
output = 1 # this will generate your eventual output

for sublist in nested_lst:
    sublst_out = 0
    for x in sublist:
        sublst_out += x # your addition of the sublist elements
    output *= sublst_out # multiply the sublist-addition with the other sublists
print(output)

Upvotes: 1

Related Questions