Home > database >  Nested list: How to sum all of the element in index 1 & 2 in these list by using for loop?
Nested list: How to sum all of the element in index 1 & 2 in these list by using for loop?

Time:01-08

Each table row contains sales data from stores in different cities:

-The element with index 1 contains sales for the first six months. -The element with index 2 contains sales for the next six months.

Find the total sales for the year, and add the results to the end of each sublist.

sales = [
    ['New York', 105820, 112180],
    ['Los Angeles', 85899, 91021],
    ['Tampa', 35010, 32001],
    ['Washington', 37011, 39595]
]
    
# write your code here

print(sales)

I'm trying to use this code, but its results error:

for i in sales:
    i = sum(sales[1],[2])
    
print(sales)

Output: Traceback (most recent call last): File "main.py", line 9, in i = sum(sales[1],[2]) TypeError: can only concatenate list (not "str") to list

CodePudding user response:

To calculate sum of second and third column in each row you can:

 for item in sales:
    item.append(item[1]   item[2])

To calculate overall sum you can simply:

 for item in sales:
    sum = sum   item[-1]

your output is like below and sum holds summation of given numbers.

 [['New York', 105820, 112180, 218000],
 ['Los Angeles', 85899, 91021, 176920],
 ['Tampa', 35010, 32001, 67011],
 ['Washington', 37011, 39595, 76606]]

 sum = 538537

Alternative solution: you can convert sales to numpy array and use numpy methods on new array.

CodePudding user response:

One of the simplest ways to get the result:

sales = [
    ['New York', 105820, 112180],
    ['Los Angeles', 85899, 91021],
    ['Tampa', 35010, 32001],
    ['Washington', 37011, 39595]
]

for i in range(len(sales)): # Loop through indexes
    result = sum(sales[i][1::]) # Calculate sum
    sales[i].append(result) # Add the result in the end

print(sales)

Output:

[['New York', 105820, 112180, 218000],
 ['Los Angeles', 85899, 91021, 176920],
 ['Tampa', 35010, 32001, 67011],
 ['Washington', 37011, 39595, 76606]]

CodePudding user response:

Try:

sales = [[s, a, b, a   b] for s, a, b in sales]
print(sales)

Prints:

[
    ["New York", 105820, 112180, 218000],
    ["Los Angeles", 85899, 91021, 176920],
    ["Tampa", 35010, 32001, 67011],
    ["Washington", 37011, 39595, 76606],
]
  • Related