python中的递归多变量lambda函数

时间:2020-12-21 18:04:51

I have seen an elegant solution for recursive functions using lambda in Python. As a matter of fact, I am very interested at applying this concept in multi-variable function, two variables — x and y — for instance. How can it be done in python?

我在Python中看到了使用lambda的递归函数的优雅解决方案。事实上,我非常有兴趣在多变量函数中应用这个概念,例如两个变量 - x和y。怎么能在python中完成?

The function itself is not important, but if it helps, here it comes the description: I have dictionaries containing one-layer dictionaries inside, as:

函数本身并不重要,但是如果有帮助的话,这里有描述:我的词典里面包含单层词典,如:

dicts = [{'A': {'a': 1}, 'B': {'a': 10}}, {'A': {'b':3}}, {'B': {'c': 31}}, {'A': {'j': 4, 't': 9}}, {'B': {'y': 400, 'r': 160}}]

And the keys in the inner dictionary does not repeat for the same given outer dictionary key. I want then to be merged, in a way that they result in:

并且内部字典中的键不会重复相同的外部字典键。我希望以一种他们导致的方式合并:

result = {'A': {'a': 1, 'b': 3, 'j': 4, 't': 9}, 'B': {'a': 10, 'c': 31, 'r': 160, 'y': 400}}

The challenge of using lambda function to solve this kept my attention and focus. So if someone could give hints or help me solving this, I do appreciate!

使用lambda函数解决这个问题的挑战引起了我的注意和关注。因此,如果有人可以给出提示或帮我解决这个问题,我很感激!

1 个解决方案

#1


0  

Python lambda functions can only consist of a single expression. So when you want to do something complex with a lambda, what you are looking for is a one-liner.

Python lambda函数只能由单个表达式组成。因此,当你想用lambda做一些复杂的事情时,你所寻找的是一个单行。

from functools import reduce # Only needed in Python3

f = lambda dicts: reduce(lambda acc, el: {**acc, **{k: {**acc.get(k, {}), **v} for k, v in el.items()}}, dicts, {})

f(dicts) # {'A': {'a': 1, 'b': 3, 'j': 4, 't': 9}, 'B': {'a': 10, 'c': 31, 'r': 160, 'y': 400}}

Note that there is an implicit recursion with the reduce function. This provides you with an example of a multi-variable lambda.

请注意,reduce函数有一个隐式递归。这为您提供了一个多变量lambda的示例。

#1


0  

Python lambda functions can only consist of a single expression. So when you want to do something complex with a lambda, what you are looking for is a one-liner.

Python lambda函数只能由单个表达式组成。因此,当你想用lambda做一些复杂的事情时,你所寻找的是一个单行。

from functools import reduce # Only needed in Python3

f = lambda dicts: reduce(lambda acc, el: {**acc, **{k: {**acc.get(k, {}), **v} for k, v in el.items()}}, dicts, {})

f(dicts) # {'A': {'a': 1, 'b': 3, 'j': 4, 't': 9}, 'B': {'a': 10, 'c': 31, 'r': 160, 'y': 400}}

Note that there is an implicit recursion with the reduce function. This provides you with an example of a multi-variable lambda.

请注意,reduce函数有一个隐式递归。这为您提供了一个多变量lambda的示例。