对列表中的元素求和,并在Python中找到最大值

时间:2011-10-17 18:03:25

标签: python list sum max

我不知道该怎么做: 我的list list定义如下:

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

日期和费用为int,类型为string

我需要按天找到最高费用。一个例子:

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

我需要总结当天的元素,并找出费用最高的日子。

结果应为:

day:1, total expenses:75

3 个答案:

答案 0 :(得分:5)

这不是一个简单的默认指示吗?

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

结果:

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

答案 1 :(得分: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))

答案 2 :(得分: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

或者如果你只想要最昂贵的一天。

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