简体   繁体   中英

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 list s 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

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)
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))
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM