【发布时间】: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- 需要将原始值除以金额才能获得新值。
如何将这个腌制文件拆分为这些变量?
【问题讨论】: