把一个pickled数组拆分成单独的变量?

2024-06-26 13:35:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用Python创建一个程序,允许用户输入一个菜谱需要服务的人数,并根据原来的服务数量重新计算原始配方的数量。在

例如,最终计算结果如下:

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

第一段代码用于将配方服务对象、配料和配料细节写入一个腌制文件。成分详细信息被循环并存储在数组中,这样就可以存储多个成分。在

^{pr2}$

这一切都是正确的,食谱所服务的人和配料都存储在腌制文件中。但是,问题在于从数组中提取信息。需要从数组中调用变量量,以乘以新的人数。在

 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-原始值需要除以amount得到新值。在

如何将这个pickle文件拆分成这些变量?在


Tags: 文件代码namenumberfor数量os配方
3条回答

你的结构似乎是:

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

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

^{pr2}$

但是,如果您只从pickle.load取回列表recipedetails,则可以执行以下操作:

for name, amount, unit in recipeinfo:

这个问题其实与酸洗无关。在

考虑:

def return_a_tuple(a, b, c):
    return (a, (b, c))

x = return_a_tuple(1, 2, 3)

如何从x中提取ab和{}?在

正如jornsharpe所说,答案是做一些类似的事情:

^{pr2}$

而且,我怀疑

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

你的意思是

^{4}$

{到目前为止,你所看到的每一对代码中都有一对是你所看到的。在

或者,可以考虑使用^{}

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

您需要拉出包含名称、数量和单位值的tuples列表。在

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

验证是否找到列表:

^{pr2}$

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

相关问题 更多 >