从列表中的字典中获取匹配值,然后添加和平均

时间:2015-03-06 21:05:54

标签: python dictionary

我正在努力获得"周"的匹配词典列表中的键。最终,我想要做的就是把第1周的所有内容加起来,以及#34;效率"这一周,找到平均值,然后第2周相同,依此类推。

注意:实际数据集要大得多

data = [{"day": 1/2/2015, "efficiency": 35, "week": 1}, 
        {"day": 1/3/2015, "efficiency": 37, "week": 1}, 
        {"day": 1/4/2015, "efficiency": 48, "week": 2},
        {"day": 1/5/2015, "efficiency": 44, "week": 2}, 
       ]

我可以用以下的方式做到这一点:

count = 0
stop_point = len(data)
week_total = []
previous_week = False
avg_per_week = []

for item in data:
    if previous_week == False or previous_week == item['week'] and count != stop_point:
        week_total.append(item['efficiency'])
        previous_week = item['week']
        count += 1
    else:
         total = 0
         for item in week_total:
             total += item
         if count == stop_point:
            previous_week = item['week']
         avrg_efficiency = total / len(week_total)
         avg_per_week.append({"week": previous_week, "average": avrg_efficiency})
         week_total = []
         count += 1
         previous_week = item['week']

但我认为必须有一个干嘛的方法来做到这一点。谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

使用defaultdict

在一周及其项目之间创建映射
from collections import defaultdict

week_to_items = defaultdict(list)
for item in data:
    week_to_items[item['week']].append(item)

现在使用映射做任何你想做的事情,这更容易:

for week, week_items in week_to_items.iteritems():
    efficiency_average = float(sum(map(lambda x: x['efficiency'], week_items))) / len(week_items)
    print week, efficiency_average

答案 1 :(得分:1)

简单地说:

for week in set(elem['week'] for elem in data):
    matches = filter(None, (elem['efficiency'] if elem['week'] == week else None for elem in data))
    total = sum(matches)
    avg   = total / float(len(matches))
    print "Week=%d  Total=%d  Average=%s" % (week, total, avg)

哪个输出

Week=1  Total=72  Average=36.0
Week=2  Total=92  Average=46.0