Python递归数据读取 [英] Python Recursive Data Reading

查看:152
本文介绍了Python递归数据读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您曾经玩过《我的世界》,那么下面的内容会更有意义.由于你们中的许多人还没有,我将尽我所能尽力解释它.

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

I am trying to write a recursive function that can find the steps to craft any minecraft item from a flatfile of minecraft recipes. This one has me really stumped.

该平面文件有点长,所以我将其包含在要点中.

The flatfile is kinda long so I included it in this gist.

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

因此,基本上,我需要查找第一个配方,然后查找该第一个配方的所有组件的配方,依此类推,直到找到没有配方的项目.每次我需要将食谱添加到列表中时,都会得到一套说明如何制作物品的指令集.

So basically I need to look up the first recipe then look up the recipes for all the components of that first recipe and so on till you get to items with no recipes. Each time I need to append the recipe to a list so I get a sort of instruction set of what order to craft items in.

这是我现在拥有的功能(该功能不起作用)

So here is the function I have now(the one the does not work)

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

这是我想要的理想输出.这是一本字典,其中存储了商品名称和数量.

Here is the ideal output I am going for. It is a dictionary with the item name and quantity's stored in it.

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

问题是,我该怎么办?

我知道要别人为你工作很烦,所以如果你觉得这跟你做我的编码有点太接近了,那就说吧.

I know asking for people to do work for you is frowned up here, so if you feel this is a little too close to you just doing the coding for me, just say so.

推荐答案

可以使用 collections.Counter ,它支持加法:

This can be elegantly solved using collections.Counter, which supports addition:

from collections import Counter

def 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递归数据读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆