为减少功能而实施

时间:2019-05-24 07:20:16

标签: python-3.x mapreduce

我想知道如何使用reduce函数从list of object获取特定键值。

让我传递一个对象列表以简化功能,每个对象都有一个键number,值是some integer,所以I want a sum of all values

样本数据就像

result = [{'number':1},{`number`:2},{'number':3}]

所以在reduce中,我有结果为keyvalue[objects,..]的代码,我应该如何实现?

reduce = Code(
    """
    function(key,value)
    {
        return Array.sum(value);
    }
    """
)

1 个答案:

答案 0 :(得分:1)

from functools import reduce
result = [{'number':1},{"number":2},{'number':3}]
c = reduce(lambda x,y:{"number":x['number']+y['number']}, result)
print(c)

"you can also use list comprehensions"

target = sum(i['number'] for i in result)
print(dict(number=target))