Kosmot199
Kosmot199

Reputation: 9

Python way to find sum of particular item in lists

I have a code that will take as many lists as people want and store it into one large list. What I want to be able to do is for each sub list in the main list, find the sum of the last item, which in this case each sub list has only 4 objects [product name, units, cost, price] and then multiply it by the number of units. I was thinking along the lines of trying it like:

for item in mainList:
   expectedProfit = (sum(item[3])) * (item[1])

Is there a cleaner way to do this by chance, or am I way off in my approach?

Upvotes: 0

Views: 79

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125128

Use a generator expression to do the multiplication, then pass that result to sum():

expected_profit = sum(item[-1] * item[1] for item in mainList) 

So for each item in mainList, it'll multiply the last item (price) by the unit count (item[1]), and all those are then summed.

Demo:

>>> mainList = [
...      # product, count, cost, price
...      ['Frobnar', 3, 2.55, 4],
...      ['Fooznib', 20, 0.66, 2.5],
...      ['Spam (canned)', 5, 3.98, 6.99],
... ]
>>> sum(item[-1] * item[1] for item in mainList)
96.95

Upvotes: 2

Related Questions