这是一个作业(尽管完全颠倒了,所以我仍然必须考虑提供的任何解决方案并在这里实际学习一些东西......)并且我花了过去三个小时在网络上做各种教程并翻阅Python 手册、Daniweb 和此处,只是无法弄清楚如何综合这些概念。
我有一堆来自文本文件的输入(假设它是下面的),每行的第一项将变成字典的键,后三项进入一个“水果”类正如你想象的那样,最终描述了这些事情。
lemon?yellow?sour?not
lemon?yellow?sour?yes
orange?orange?sweet?yes
grape?purple?sweet?yes
我希望从此文件创建的键“柠檬”将描述符“黄酸不”和“黄酸是”作为列表返回。
class Fruit(object):
'''Describes fruits'''
def __init__(self,color,flavor,tasty):
self.color = color
self.flavor = flavor
self.tasty = tasty
def getColor(self): return self.color
def getFlavor(self): return self.flavor
def getTasty(self): return self.tasty
def description(self): return self.color,self.flavor,self.tasty
fruity = {}
for line in inputFile:
n,c,f,t = line.split('?')
indFruit = fruit(c,f,t)
fruity[n] = [fruit.description]
到目前为止,所有这些都有效,当然除了文件第二次点击“柠檬”键时,它会用“黄酸是”覆盖“黄酸不”(换句话说,它似乎正在做它应该做的一切去做。)
所以我正在研究一种解决柠檬问题的方法。我试过了:
fruity = {}
fruitlist = []
for line in inputFile:
n,c,f,t = line.split('?')
indFruit = fruit(c,f,t)
fruity[n] = fruitlist.append(indFruit)
产生
{(lemon): none, (orange): none, (grape): none}
接着
fruity = {}
fruitlist = []
for line in inputFile:
n,c,f,t = line.split('?')
indFruit = fruit(c,f,t)
fruitlist.append(indFruit)
fruity[n] = fruitlist
这是一个有点过分的人,因为它产生了:
{(lemon): [(yellow, sour, not),(yellow,sour,yes),(orange,sweet,yes),(grape,sweet,yes)}
我无法弄清楚如何让它做我想要的,即显示:
{(lemon): [(yellow, sour, not),(yellow,sour,yes)], (orange): [(orange, sweet, yes)]}
and so on.
提前致谢!