Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I find the sum of only certain values in a list of lists AND only when a certain string is in there?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading