razvstar
razvstar

Reputation: 13

Sum elements in a list of lists and find maximum in Python

I don't know how to do this: I have a list of lists defined like this:

list=[[day,type,expense],[...]];

day and expense are int, type is string

I need to find the max expense by day. An example:

list=[[1,'food',15],[4,'rent', 50],[1,'other',60],[8,'bills',40]]

I need to sum the elements that have the same day and find the day with the highest expenses.

The result should be:

day:1, total expenses:75

Upvotes: 1

Views: 2924

Answers (3)

jro
jro

Reputation: 9474

Isn't a defaultdict just as easy?

import pprint
from collections import defaultdict
from operator import itemgetter

l = [[1, 'food', 15], [4, 'rent', 50], [1, 'other', 60], [8, 'bills', 40]]
d = defaultdict(int)
for item in l:
    d[item[0]] += item[2]
pprint.pprint(dict(d))
print max(d.iteritems(), key=itemgetter(1))

Result:

{1: 75, 4: 50, 8: 40}
(1, 75)

Upvotes: 5

Tyler Ferraro
Tyler Ferraro

Reputation: 3772

list = [[1, 'food', 15], [4,'rent', 50], [1, 'other', 60], [8, 'bills', 40]]
hash = {}
for item in list:
    if item[0] not in hash.keys():
        hash[item[0]] = item[2]
    else:
        hash[item[0]] += item[2]

for (k, v) in hash:
    # print key: value

or if you just want the most expensive day.

for (k, v) in hash:
    if (v == max(hash.values()):
        #print k: v

Upvotes: 0

Jochen Ritzel
Jochen Ritzel

Reputation: 107588

data=[[1,'food',15],[4,'rent', 50],[1,'other',60],[8,'bills',40]]

# put same days together
data.sort()


# aggregate the days
from itertools import groupby
from operator import itemgetter

grouped = groupby(data, key=itemgetter(0))


# sum values by day
summed = ((day, sum(val for (_,_,val) in day_group))
          for day, day_group in grouped)


# get the max
print max(summed, key=itemgetter(1))

Upvotes: 2

Related Questions