【问题标题】:Iterating through a Python 3 dictionary, recursion and return [duplicate]遍历 Python 3 字典、递归和返回 [重复]
【发布时间】:2018-12-02 22:19:54
【问题描述】:

TL;DR 在最后!

嗨,我遇到了递归函数和字典的问题,当找到特定键时,它应该返回一个值,但我得到的只是无。

假设我正在构建一个在 localhost:8080/MyGame/ 上运行的游戏,并且我有 HTML 文件可以放在该地址的末尾,例如 localhost:8080/MyGame/Archer.html

我将使用 localhost:8080/MyGame/ + Archer.html 构建我的 HTML 链接,并且我有一个字典,其中包含它的基础和每个页面的值,例如 Archer.htmlKnight/Main_Castle.html 和 @987654327 @ 和 knight_sc 分别作为它的键(“sc”代表次要城堡,“mc”代表主城堡)

我制作了一个 python 文件来进一步表达我遇到的问题,它包含我试图迭代的字典、递归函数和主要方法

所以,我的字典是这样的:

URLS = {
    'base': 'localhost:8080/MyGame/',
    'main_castle': {
        'defenses_mc': {
            'bombard_tower_mc': 'Bombard_Tower.html',
            'fire_roaster_mc': 'Fire_Roaster.html',
            'freeze_tower_mc': 'Freeze_Tower.html'
        },
        'army_mc': {
            'troops_mc': {
                'mage_mc': 'Mage.html',
                'witch_mc': 'Witch.html',
                'knight_mc': 'Knight/Main_Castle.html',
                'berserker_mc': 'Berserker/Main_Castle.html',
            },
            'commandants': {
                'wizard_mc': 'Wizard.html',
                'warlock_mc': 'Warlock.html',
                'dragon_mc': 'Dragon.html'
            },
            'spells': {
                'upgrade_spell': 'Upgrade_Spell.html',
                'damage_spell': 'Damage_Spell.html'
            }
        },
    },
    'secondary_castle': {
        'defenses_sc': {
            'archer_tower_sc': 'Archer_Tower.html',
            'barracks': 'Barracks.html'
        },
        'army_sc': {
            'troops_sc': {
                'archer_sc': 'Archer.html',
                'knight_sc': 'Knight/Secondary_Castle.html',
                'berserker_sc': 'Berserker/Secondary_Castle.html'
            }
        }
    }
}

我的递归函数如下所示:

def recursion(dictionary, key_to_find):
    for key, value in dictionary.items():
        if key_to_find == key:
            print("Found! '" + key_to_find + "' value is '" + value + "'")
            return value
        elif isinstance(value, dict):
            recursion(value, key_to_find)
    return "Sorry, couldn't find anything :("

有一点需要注意,我稍后会提到:上面的代码遍历整个字典。

递归函数有两个参数:一个我想遍历的字典,一个我想找到它的值的特定键。

主函数如下所示:

def main():
    knight_sc = str(recursion(URLS, 'knight_sc'))
    knight_sc_url = URLS['base'] + knight_sc
    print(knight_sc_url)

预计knight_sc 将等于“Knight/Second_Castle.html”,因为当我运行递归函数时,它实际上会找到并打印键 knight_sc 的实际值,即“Knight/Second_Castle.html”。 html',但它只返回None

事情就是这样,我已经搜索过它,到处都说你不能简单地在另一个函数中调用一个函数并称之为递归,因为那可能只是 functionA 调用 functionB 等等......

但是,当我在调用函数之前放置 return

elif isinstance(value, dict):
    recursion(value, key_to_find) # <- return should go at the start of this line

它只迭代到freeze_tower_mc 并停止在那里迭代。至少函数调用中没有return 的版本会遍历整个字典,发现key 等于key_to_find 并打印它的值,而不是返回该值。

例如,如果我在调用recursion() 之前调用recursion() WITH 返回标记,但现在在我的主方法中传递'fire_roaster_mc' 作为参数,它实际上返回'Fire_Roaster。 html',我可以使用URLS['base'] + str(recursion(URLS, 'fire_roaster_mc'))构建HTML链接

我真的错过了一些我看不到的愚蠢的东西,因为经过多次尝试后我的大脑变得麻木,但没有任何效果,还是这是一个常见问题?有解决办法吗?

另外我应该说我是 Python 的新手,来自 Java,我只是为了好玩而编写代码(从未做过像工作、项目或大学这样严肃的事情),到目前为止我已经 真的喜欢 Python,因为它简单易用:D

TL;DR:如果找到特定键,我应该返回一个值的递归函数正在返回 None,但它正在找到实际的键,我可以打印它的值

抱歉有任何语法错误,因为英语不是我的母语。

提前致谢!

【问题讨论】:

  • OT:最好将 tl;dr: 放在问题和答案之上,然后是详细信息 :)
  • 您忽略了递归结果。需要return recursion(value, key_to_find)...如果这不起作用,则错误在其他地方,但这是必需的
  • @cricket_007 当我把 return 放在它前面时,它只迭代到一个特定的键,即 'freeze_tower_mc' 键,然后,而不是去下一个字典,即 'army_mc ',它只是停止迭代。可能是逻辑错误?
  • recursion() 的第二次调用中,您忽略了返回值,并且您的函数继续执行循环。您应该在第二个 recursion() 之后添加一个 if 语句来检查是否找到该值。
  • 你需要return你的递归调用recursion。如果在递归调用中找不到密钥,您还需要继续迭代。最好在找不到密钥时引发异常。 def recursion(dictionary, key_to_find): for key, value in dictionary.items(): if key_to_find == key: return value if isinstance(value, dict): try: return recursion(value, key_to_find) except RuntimeError: pass raise RuntimeError ('未找到密钥')

标签: python dictionary recursion iteration


【解决方案1】:

它停在freeze_tower_mc,因为那是最里面的字典,而您返回了Sorry, couldn't find anything,因为您已经遍历了该字典的所有元素。然后将返回结果传回调用堆栈,从而结束循环。

我认为相反,如果您想跟踪您在整个字典中没有找到任何内容,请传入一个深度参数,然后仅在该循环结束时返回您没有找到任何内容并且您返回字典的顶部

def recursion(dictionary, key_to_find, depth=0):
    for key, value in dictionary.items():
        if key_to_find == key:
            print("Found! '{}' value is '{}'".format(key_to_find, value)) 
            return value
        elif isinstance(value, dict):
            print("Searching " + str(value) + " at depth " + str(depth+1)) 
            found = recursion(value, key_to_find, depth=depth+1)
            if found is not None:
                # if it is found, you'd see this line printed twice, once in the recursion, then once here 
                print("Found! '{}' value is '{}'".format(key_to_find, found)) 
                return found
    if depth == 0:
        return "Sorry, couldn't find anything" 

【讨论】:

  • print("Found! '" + key_to_find + "' value is '" + str(value) ) : 否则如果 value 是 dict 会报错
  • 第二个返回值应该是返回找到的.....不是吗?
  • 复制粘贴问题:)
  • 在 if key_to_find == key: .... 之后,你仍然缺少 str(value),这很好:)
  • OP 并没有真正指定搜索字典,但无论如何都已修复
猜你喜欢
  • 2023-03-29
  • 1970-01-01
  • 2013-03-04
  • 1970-01-01
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
  • 2019-02-15
  • 1970-01-01
相关资源
最近更新 更多