[英]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
的list
这样定义S:
list=[[day,type,expense],[...]];
day and expense are int
, type is string
日和费用为int
,类型为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? defaultdict难道不是那么容易吗?
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.