Home > Back-end >  trying to get a total for each row in a list then add them all up at the end to get the absolute tot
trying to get a total for each row in a list then add them all up at the end to get the absolute tot

Time:12-07

The text file is formatted like so: artist, title, genre, play length, condition, stock, cost

i need to get the total cost for the records in stock so a total for each row then add them all up to get the absolute total cost at the end

in my code i have been able to get the total cost of the records by just summing up the value assuming that there is only one of each record in stock however im not sure how to get the sum of stock * cost for each record or row in a function

here is my code:

def print_summary():
value = 0
for item in range(len(record_inventory_list)):
    print(record_inventory_list[item][0], record_inventory_list[item][1], record_inventory_list[item][2], record_inventory_list[item][3], record_inventory_list[item][4], record_inventory_list[item][5], record_inventory_list[item][6], sep=' -> ')
    value  = float(record_inventory_list[item][6])
    
print('\nTotal Value of records: ', format(value, '.2f'))
print('Amount of titles: ', len(record_inventory_list))

CodePudding user response:

You can use list comprehension:

def total_cost():
    return sum(lst[5]*lst[6] for lst in record_inventory_list)
        
print(total_cost())

Just FYI, it's cleaner to iterative over the list directly, rather than its indices. Like:

def print_summary():
    value = 0
    for item in record_inventory_list:
        print(item, sep=' -> ')
        value  = float(item[6])
    return value
    
  • Related