我想知道如何使用reduce函数从list of object
获取特定键值。
让我传递一个对象列表以简化功能,每个对象都有一个键number
,值是some integer
,所以I want a sum of all values
。
样本数据就像
result = [{'number':1},{`number`:2},{'number':3}]
所以在reduce中,我有结果为key
而value
为[objects,..]
的代码,我应该如何实现?
reduce = Code(
"""
function(key,value)
{
return Array.sum(value);
}
"""
)
答案 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))