Python 如何在字典中使用reduce

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26583381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:42:20  来源:igfitidea点击:

how to use reduce with dictionary

pythondictionaryreduce

提问by Salvador Dali

I have some problem understanding how to use reduce with dictionaries in python. For example I have the following dictionary.

我在理解如何在 python 中使用 reduce 和字典时遇到了一些问题。例如,我有以下字典。

{1: 3, 2: 1, 3: 2}

{1: 3, 2: 1, 3: 2}

and I am trying to calculate the following:

我正在尝试计算以下内容:

s = 0
for i in h:
    s += h[i] * (h[i] - 1)

This works as expected (I get: 8), but I my attempt to convert it to reduce paradigm fails: reduce(lambda x, y: x + y * (y - 1), h), but I am getting the wrong answer.

这按预期工作(我得到:)8,但我尝试将其转换为减少范式失败: reduce(lambda x, y: x + y * (y - 1), h),但我得到了错误的答案。

I assume this is because I am using keys, not values. How can I convert my code to reduce properly?

我认为这是因为我使用的是键,而不是值。如何转换我的代码以正确减少?

采纳答案by Abhijit

You need to iterate over the dictionary while reducing it with an initial value of zero.

您需要迭代字典,同时将其初始值为零。

Note, iterating over a dictionary, actually iterates over the keys so you need to index the dictionary to get the value

注意,遍历字典,实际上是遍历键,所以你需要索引字典来获取值

reduce(lambda x, key:x + h[key] * (h[key] - 1), h, 0)

Alternatively, as you are only interested in the values of the dictionary, caring least about the key, just iterate on the values of the dictionary

或者,由于您只对字典的值感兴趣,而不关心键,只需迭代字典的值

Python 2.X

蟒蛇2.X

reduce(lambda x, value:x + value * (value - 1), h.itervalues(), 0)

Python 3.X

蟒蛇 3.X

reduce(lambda x, value:x + value * (value - 1), h.values(), 0)