【发布时间】:2016-07-26 15:32:33
【问题描述】:
我的奋斗:
阅读两行并跳过第三行。
然后我想将所有对象存储在字典中,名称为键。
**** Ingredients.txt ****
Name1
ingredient1/ingredient2/ingredient3
Name2
ingredient1/ingredient2
Name3
...
class Foodset(object):
def __init__(self, name):
self.name = name
self.ingredients = set([])
def __str__(self):
return str(self.name) + ' consits of: ' + ", ".join(str(e) for e in self.ingredients) + '.'
def setIngredients(self, list):
for i in list:
self.ingredients.add(i)
def getMenu(file="ingredients.txt"):
with open(file, 'r') as indata:
menu = dict()
for line in indata:
tempString = str(line.rstrip('\n'))
menu[tempString] = Foodset(tempString)
我想阅读下一行并将其存储为成分,然后跳过第三行,因为它是空白的。然后重复。
我在使用 for 循环时遇到的问题是,我不能在同一个循环中存储两条不同的行,然后引用同一个对象以使用 setIngredients() 方法。 我可以通过哪些其他方式读取每个循环中的多行?
编辑: @Arpan 提出了一个快速的解决方案,使用 indata.readlines() 列出每行的列表,并以 3 步为循环,同时存储第一个和第二个值并跳过第三个。
我刚刚想出了另一个解决方案,在 while 循环中使用 readline() 方法 3 次。使用 readline() 是我最初想要的。
def getMenu(menu="ingredients.txt"):
with open(menu, "r") as indata:
menu = dict()
while True:
name = indata.readline().strip('\n')
ingredientList = indata.readline().strip().split('/')
if name == "":
break
# here I just added a parameter that directly set the attribute "ingredients" inside the object.
menu[name] = Foodset(name, ingredientList)
indata.readline()
return menu
【问题讨论】:
-
这是多个问题合而为一的问题。你能隔离问题吗?是读取文件的问题,一次得到三行问题吗?构建您的自定义对象是问题吗?如果您编辑问题以仅包含您正在努力解决的部分的最小示例,您将更快地获得帮助。
标签: python list for-loop dictionary readline