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?
我认为这是因为我使用的是键,而不是值。如何将我的代码转换为正确缩减?
1 个解决方案
#1
20
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
reduce(lambda x, value:x + value * (value - 1), h.itervalues(), 0)
Python 3.X
reduce(lambda x, value:x + value * (value - 1), h.values(), 0)
#1
20
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
reduce(lambda x, value:x + value * (value - 1), h.itervalues(), 0)
Python 3.X
reduce(lambda x, value:x + value * (value - 1), h.values(), 0)