简体   繁体   English

Python字典中的递归

[英]recursion in Python dictionary

I am implementing a switch/case expression through dictionary in Python. 我正在通过Python在字典中实现一个switch / case表达式。 Can anyone tell me why the following recursive call is wrong? 谁能告诉我为什么下面的递归调用是错误的?

I am getting an exception: RuntimeError: maximum recursion depth exceeded 我遇到异常: RuntimeError: maximum recursion depth exceeded

def rec(x):
    return {
        'a': 'one',
        'b': 'two',
        'ac': rec('a'),
    }.get(x,x)

The reason you're getting infinite recursion is because you're telling Python to store the result of the recursive call rec('a') in the dictionary. 获得无限递归的原因是因为您要告诉Python将递归调用rec('a')结果存储在字典中。 This means it recurses unconditionally, since you always build the dictionary before doing the lookup. 这意味着它无条件地递归,因为您总是在进行查找之前先构建字典。

One way to solve this would be to store lambda functions in the dictionary, and then only call the one you get . 解决此问题的一种方法是将lambda函数存储在字典中,然后仅调用get In this version, the recursive call is only made when the appropriate x value is passed in: 在此版本中,仅当传入适当的x值时才进行递归调用:

def rec(x):
    return {
        'a': lambda: 'one',
        'b': lambda: 'two',
        'ac': lambda: rec('a'),
    }.get(x, lambda: x)()

Unfortunately, that's a bit cumbersome. 不幸的是,这有点麻烦。 I'm not sure I'd bother if there were just have three cases and a default. 我不确定是否只有三个案例和一个默认案例。 I'd just use a series of if statements, even though that might not be as efficient as a dictionary lookup. 我只是使用一系列的if语句,即使那可能不像字典查找那样有效。

Your dict values are not put in lazily, which means it always creates the dict 您的字典值不会被懒惰地放入,这意味着它总是创建字典

{
    'a': 'one',
    'b': 'two',
    'ac': rec('a'),
}

whether you look up 'ac' or not. 无论您是否查找'ac' As such, you can't just look up 'a' in your recursive call -- you have to make the dict (recursing another layer) first. 因此,您不能仅在递归调用中查找'a' ,而是必须首先做出dict(递归另一层)。

You'll have to write this code another way. 您必须以另一种方式编写此代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM