1

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
0

3 Answers 3

5

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)
Sign up to request clarification or add additional context in comments.

2 Comments

max(d.iteritems(), key = operator.itemgetter(1))
Thanks, missed the final step.
2
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))

1 Comment

I like groupby too, but if the data is unsorted I think a defaultdict is more natural. Random suggestions: I'd use an itemgetter key function for the sort too so as to avoid doing extra comparisons. Also, if you're going to use itemgetter for the key functions (I realize those have to be functions), why not also use it for the summing (even though you don't have to use a function there)? valgetter = itemgetter(2) then a generator expression or map with valgetter -- sum(map(valgetter, day_group)).
0
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

1 Comment

Since i'm a beginner in python, i find this answer to my understanding. Thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.