[英]using reduce to sum values in a list of dictionaries
假设我有一个字典列表
parents = [
{'Name': 'Peter', 'Kids': 2},
{'Name': 'Mary', 'Kids': 1},
{'Name': 'Lia', 'Kids': 3}
]
我正在使用 map 通过使用 map 将那些有 2 个以上孩子的值更改为 1。 接下来,我尝试使用 reduce 来计算孩子的总数。
我已经设法让过滤器和 map 工作,但我被困在减少部分,有人有什么建议吗?
这就是我现在所拥有的
total = reduce(lambda x, y: x+y["Kids"], map(lambda x: x["Kids"]-2, filter(lambda x:x["Kids"] > 2, parents)))
但是,它返回我 1。
我建议你使用reduce
如下:
from functools import reduce
from operator import add
filtered = filter(lambda x: x["Kids"] >= 2, parents)
edited = map(lambda _: 1, filtered)
res = reduce(add, edited)
print(res)
Output
2
在一行中:
total = reduce(add, map(lambda _: 1, filter(lambda x: x["Kids"] >= 2, parents)))
print(total)
如果您想避免导入 add do(完整示例):
add = lambda x, y : x + y
filtered = filter(lambda x: x["Kids"] >= 2, parents)
edited = map(lambda _: 1, filtered)
res = reduce(add, edited)
print(res)
请注意,上面我使用的所有示例>=
大于或等于。
如果你想用functools.reduce
做到这一点。
from functools import reduce
# first
reduce(lambda x,y : x+y['Kids'] , parents, 0)
# 6
# with your filter
reduce(lambda x,y : x+y['Kids'] , filter(lambda x:x["Kids"] > 2, parents), 0)
# 3
reduce(lambda x,y : x+y , map(lambda x: x['Kids']-1,
filter(lambda x:x["Kids"] > 2,
parents)), 0)
# 2
首先这是如何工作的:
x = 0
y = 2
x = 0+2
y = 1
x = 0+2+1
y = 3
result = 0+2+1+3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.