I think I didn’t express myself very well in the title, but basically here’s what I need to do.
I have a veeeery big list of lists containing at index 1 the name of the comic, index 2 the unit price, index 3 the quantity sold and index 4 the total paid.
[['1', 'Tintin', '9.95', '3', '29.85'], ['2', 'Asterix', '12.5', '3', '37.5'], ['3', 'Asterix', '12.5', '3', '37.5'], ['4', 'Asterix', '12.5', '2', '25']
And I need to find the sum of the units sold and the total money paid.
For example, here Asterix would be:
['Asterix', 12.5, 8, 100]
Any ideas?
>Solution :
Make a function that takes in a given name and some data and iterates over it performing the logic you described. Just make sure to coerce to proper number types prior to performing addition.
def stats(comic_data, name):
unit_price = None
num_sold = 0
revenue = 0
for comic in comic_data:
_, cname, unit_p, num, amnt = comic
if cname == name:
if unit_price is None:
unit_price = float(unit_p)
num_sold += int(num)
revenue += float(amnt)
return [name, unit_price, num_sold, round(revenue, 2)]
stats(data, "Asterix")
>> ['Asterix', 12.5, 8, 100.0]