0

I need calculate the total sums separately with the values in cluster1. Profit is the first number in each list inside the cluster1 nested list and quantity will be the second number.

The output I expected was 11 with print(totalprofit1) and 8 with print(totalprofit2). However, I got an empty list [] as the output and I am not sure how to fix this.

Below is the current code I have so far:

cluster1=[[1,2],[1,6],[9,0]]

totalprofit1=[]
totalquantity1=[]
for profit,quantity in int1:
   if isinstance((profit,quantity), list):
      totalprofit1.append(sum(profit))
      totalquantity1.append(sum(quantity))
print(totalprofit1)
print(totalquantity1)
medium-dimensional
  • 1,974
  • 10
  • 19
Sam
  • 15
  • 5

2 Answers2

2

It appears your biggest flaw is that a tuple of profit and quantity will never be an instance of list, so nothing ever executes in your loop.

I would suggest simply zipping the list of lists.

>>> list(zip(*cluster1))
[(1, 1, 9), (2, 6, 0)]

Now you can map sum to those.

>>> list(map(sum, zip(*cluster1)))
[11, 8]

And then just bind names to the sums:

>>> total_profit, total_quantity = map(sum, zip(*cluster1))
>>> total_profit
11
>>> total_quantity 
8
Chris
  • 26,361
  • 5
  • 21
  • 42
1

There are numerous ways of doing this. This is probably the simplest.

Iterate over cluster1 and unpack the 2 values found in each sublist. Increment accumulators accordingly.

cluster1 = [[1, 2], [1, 6], [9, 0]]

totalProfit = 0
totalQuantity = 0

for p, q in cluster1:
    totalProfit += p
    totalQuantity += q

print(f'{totalProfit=}')
print(f'{totalQuantity=}')

Output:

totalProfit=11
totalQuantity=8

Optionally:

cluster1=[[1,2],[1,6],[9,0]]

totalProfit = sum(e[0] for e in cluster1)
totalQuantity = sum(e[1] for e in cluster1)

print(f'{totalProfit=}')
print(f'{totalQuantity=}')

The optional approach is significantly slower than the original suggestion

DarkKnight
  • 19,739
  • 3
  • 6
  • 22