我使用的文本文件有4行,但根据用户的不同,它可能更少也可能更多。
我的代码:
def loadrecipefile (recipe_file):
infile=open(recipe_file)
Linelist=infile.readlines()
global cookbook
for line in Linelist:
wordList=line.split()
r1={'apple':int(wordList[1]),'beets':int(wordList[2]),'carrots':int(wordList[3])}
cookbook={wordList[0]:r1}
def printrecipes():
for name,ingred in cookbook.items():
print(name + " " + str(ingred['apple']) + " " + str(ingred['beets']) + " " + str(ingred['carrots']))
因此,输入将是(在我的例子中):
loadrecipefile("recipe_file.txt")
printrecipes()
然后,它将打印文本文件的每一行,我希望它看起来像这样:
Recipe1 1 4 3
Recipe2 0 2 4
Recipe3 3 0 1
Recipe4 2 1 0
但我只得到了最后一行:Recipe4 2 1 0
发布于 2018-08-30 03:55:19
您将在每个循环中覆盖cookbook
变量的内容:
cookbook={wordList[0]:r1}
这将执行N次,每次都会创建一个包含一个键/值的新字典。
相反,您应该在each循环中添加到现有字典:
cookbook = {}
for ...:
cookbook[wordList[0]] = r1
现在,你没有问到的部分,但你应该修复它,因为它看起来很糟糕:不要使用全局变量。什么时候?如果你从来不用它们,你就不会错。
不是将结果存储在全局变量中,而是从函数返回结果:
def loadrecipefile(recipe_file):
...
return cookbook
然后,在另一个函数中,获取结果:
def printrecipes(recipefile):
cookbook = loadrecipefile(recipefile)
for name, ingred in cookbook.items():
...
或者执行以下操作:
def printrecipes(cookbook):
for name, ingred in cookbook.items():
...
然后:
cookbook = loadrecipefile(recipe_file)
printrecipes(cookbook)
https://stackoverflow.com/questions/52084894
复制相似问题