根据排名对字典项求和

Sum dictionary items based on rank

我可以像这样按键对字典列表中的项目求和:

import functools
dict(
    functools.reduce(
        lambda x, y:x.update(y) or x,
        dict1,
        collections.Counter())
)

但考虑到

dict1 = [{'ledecky': 1, 'king': 2, 'vollmer': 3},
         {'ledecky': 1, 'vollmer': 2, 'king': 3},
         {'schmitt': 1, 'ledecky': 2, 'vollmer': 3}]

如何根据奖牌价值对它们的价值求和,鉴于:

medal_value = {1: 10.0, 2: 5.0, 3: 3.0}

这样最终的命令会产生:

{'ledecky': 25.0, 'king': 8.0, 'vollmer': 11.0, 'schmitt': 10.0}

get() 字典函数在这个例子中效果很好,我们要么给新创建的字典一个默认值 0,要么用我们的 [=14] 添加它的当前值和加权值=](的值dict1)作为搜索关键字。

def calculate_points(results, medal_value):
    d = {}
    for item in results:
        for key, value in item.iteritems():
            d[key] = d.get(key, 0) + medal_value[value]
    return d

示例输出:

dict1 = [{'ledecky': 1, 'king': 2, 'vollmer': 3},
     {'ledecky': 1, 'vollmer': 2, 'king': 3},
     {'schmitt': 1, 'ledecky': 2, 'vollmer': 3}]

medal_value = {1 : 10.0, 2 : 5.0, 3 : 3.0}

print calculate_points(dict1, medal_value)
>>> {'ledecky': 25.0, 'king': 8.0, 'schmitt': 10.0, 'vollmer': 11.0}

只需定义一个查找函数,将原始字典转换为奖牌值字典:

def lookup(d):
    return dict((k, medal_value[v]) for k, v in d.items())

并将此函数应用于表达式的更新部分:

dict(
    functools.reduce(
        lambda x, y: x.update(lookup(y)) or x, 
        dict1,
        collections.Counter())
)