【问题标题】:Splitting up a pickled array into separate variables?将腌制数组拆分为单独的变量?
【发布时间】:2014-04-23 00:49:47
【问题描述】:

我正在尝试使用 Python 创建一个程序,该程序将允许用户输入食谱需要服务的人数,并根据其旧的服务人数重新计算原始食谱的数量。

例如,最终的计算将是这样的:

(ingredient quantity / old serve number) * new serve number

第一段代码用于将食谱服务的人员、配料和配料详细信息写入腌制文件。成分详细信息被循环并存储在一个数组中,以便可以存储多种成分。

 serve = int (input ("Enter number of people: ")) #Prompts user for number of people the recipe will serve

 recipedetails=[]#starts array

 for i in range (ing_number): *#Loops 3 intented inputs by ing_number amount of times*
        name = input ("Enter ingredient name: ") *#Ingredient name variable*
        amount = int (input ("Enter quantity of ingredient ")) *#Quantity variable*
        unit =  input ("Enter unit of ingredient: ") *#Unit variable*

        recipedetails.append ((name, amount, unit)) *#closes array with variables added*

        recipeinfo = serve , recipedetails *# adds serve and recipedetails to recipe info variable*

        recipe = open(rec_name+".dat", "wb") *#Creates .dat file with recipe name as file  name.*
        pickle.dump(recipeinfo, recipe) *#Adds this recipeinfo to .dat file*

这一切都正常工作,配方服务的人和成分都存储在腌制文件中。但是,问题在于从数组中调用信息。变量数量需要从数组中调出乘以新的人数。

 import os 
 textfiles = [f for f in os.listdir(os.curdir) if f.endswith (".dat") ] *#imports* 
 print (textfiles)
 rec_name = input ("Enter recipe name: ") *#Prompts user for recipe name.*
 rd = open (rec_name+ ".dat", "rb") *#Opens the file the user selected*
 recipeinfo = pickle.load(rd) *#Gives loaded file a variable so it can be displayed*

 print(recipeinfo) *# Prints recalled information*

到目前为止的代码工作正常。使用它我可以从保存的数组中查看recipeinfo。但是,我不知道如何将数组拆分回原始变量。

  • name - 成分名称显示在数量之前
  • amount - 需要除以人并乘以新的数量
  • unit - 显示在金额之后
  • serve - 需要将原始值除以金额才能获得新值。

如何将这个腌制文件拆分为这些变量?

【问题讨论】:

    标签: python arrays pickle


    【解决方案1】:

    您的结构似乎是:

    recipeinfo == (serve, [(name, amount, unit), (name, amount, unit), ...])
    

    因此,您可以使用以下方法将recipeinfo 转回这些变量:

    serve, recipedetails = recipeinfo
    for name, amount, unit in recipedetails:
    

    但是,如果您只从pickle.load 获取列表recipedetails,您可以这样做:

    for name, amount, unit in recipeinfo:
    

    【讨论】:

    • 这是我尝试分离 recipeinfo 时得到的错误
    • 请编辑您的问题以包含print(recipeinfo)的结果
    • [('Water', 400, 'ml'), ('Flour', 400, 'grams'), ('Sugar', 50, 'grams')] 这是印刷品 (recipeinfo ) 用于配方 ('Flour', 400, 'grams') 从 .dat 文件打开后打印(数量)
    • 所以您只有recipedetails 列表,而不是serve 数量?我已经更新了我的答案,但不清楚其他价值去了哪里!
    【解决方案2】:

    这个问题实际上与酸洗无关。

    考虑:

    def return_a_tuple(a, b, c):
        return (a, (b, c))
    
    x = return_a_tuple(1, 2, 3)
    

    如何从x 中提取abc

    正如 jonrsharpe 所说,答案是:

    (a, (b, c)) = x
    

    另外,我怀疑不是

    recipedetails.append((name, amount, unit))
    recipeinfo = serve , recipedetails
    

    你的意思是这样的

    recipedetail = (name, amount, unit)
    recipedetails.append(recipedetail)
    recipeinfo = serve, repcipedetail
    

    您的原始代码正在创建一对serve,其中包含您迄今为止看到的每个食谱详细信息的列表,而不仅仅是您刚刚读到的那个。

    或者,您可以考虑使用namedtuple

    from collections import namedtuple
    
    RecipeDetail = namedtuple('RecipeDetail', ['name', 'amount', 'unit'])
    RecipeInfo = namedtuple('RecipeInfo', ['serve', 'recipe_detail'])
    

    然后你可以做类似的事情

    recipedetail = RecipeDetail(name, amount, unit)
    recipedetails.append(recipedetail)
    recipeinfo = RecipeInfo(serve, recipedetail)
    

    现在您可以通过以下方式访问子字段:

    recipedetail.name
    recipeinfo.recipe_detail.amount
    

    【讨论】:

    • print(recipeinfo , "This is the current recipe") (ing_name, ing_amount, ing_unit) = recipeinfo print (ing_amount)
    • 加载泡菜文件并使用上面的代码后,我得到了这个
    • [('Water', 400, 'ml'), ('Flour', 400, 'grams'), ('Sugar', 50, 'grams')] 这是当前配方('面粉', 400, '克')
    • 由于数组中的成分数量可能是无限的,它似乎只占用了所有第二种成分。我希望它在哪里获取所有数字(金额)并将它们放在一个列表中,我可以同时对它们执行计算。
    【解决方案3】:

    您想提取包含名称、数量和单位值的元组列表

    import sys
    ingredients_list = ''
    for item in recipeinfo:
        if type(item) == list:
            ingredients_list = item
            continue
    

    验证您是否找到了一个列表:

    if ingredients_list == '':
        print("I never found a list!")
        sys.exit(1)
    
    for name, amount, unit in ingredients_list:
         print("{0}: {1} {2}").format(name, amount, unit)
        . . .
    

    并使用这些值进行计算、打印说明等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-16
      • 2015-08-17
      • 1970-01-01
      • 2016-04-22
      相关资源
      最近更新 更多