Python递归数据读取

Python递归数据读取,第1张

概述如果你玩过我的世界,以下将更有意义.由于你们许多人没有,我会尽力解释它我正在尝试编写一个递归函数,可以找到从Minecraft食谱的平面文件中制作任何minecraft项目的步骤.这个让我很难过.平面文件有点长,所以我把它包含在this gist中.def getRecipeChain(item, quantity=1): #magic recurs

如果你玩过我的世界,以下将更有意义.由于你们许多人没有,我会尽力解释它

我正在尝试编写一个递归函数,可以找到从minecraft食谱的平面文件中制作任何minecraft项目的步骤.这个让我很难过.

平面文件有点长,所以我把它包含在this gist中.

def getRecipeChain(item,quantity=1):    #magic recursive stuffs go here

所以基本上我需要查找第一个食谱然后查找第一个食谱的所有组分的食谱,依此类推,直到你找到没有食谱的食物.每次我需要将配方附加到列表中,这样我就可以得到一种关于制作物品的顺序的指令集.

所以这是我现在的功能(一个不起作用)

def getRecipeChain(name,quantity=1):    chain = []    def getRecipe(name1,quantity1=1):        if name1 in recipes:            for item in recipes[name1]["ingredIEnts"]["input"]:                if item in recipes:                    getRecipe(item,quantity1)                else:                    chain.append(item)    getRecipe(name,quantity)    return chain

这是我想要的理想输出.它是一个字典,其中存储了项目名称和数量.

>>> getRecipeChain("solar_panel",1):{"insulated_copper_cable":13,"electronic_circuit":2,"re_battery":1,"furnace":1,"machine":1,"generator":1,"solar_panel":1}

所以问题是,我该怎么做?

我知道要求人们为你做的工作在这里不受欢迎,所以如果你觉得这对你来说有点太接近我只是这么说.

最佳答案这可以使用collections.Counter优雅地解决,它支持添加:

from collections import Counterdef getRecipe(name,quantity=1):  if not name in recipes: return Counter({name: quantity})  subitems = recipes[name]["ingredIEnts"]["input"]  return sum((getRecipe(item,quantity) for item in subitems),Counter())print repr(dict(getRecipe("solar_panel")))# => {'copper': 39,'refined_iron': 10,'glass': 3,#     'rubber': 78,'cobblestone': 8,'tin': 4,#     'coal_dust': 3,'nothing': 10,'redstone': 6}
总结

以上是内存溢出为你收集整理的Python递归数据读取全部内容,希望文章能够帮你解决Python递归数据读取所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1205722.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存