2017-06-07 132 views
0

我創建了一個基本上是愛好書的類。這本書可以通過兩種方法進行訪問,enter(n,h),它需要一個名字並且不斷添加愛好到這個名字(一個名字可以有多個愛好)。另一種方法返回一組特定名稱的業餘愛好。我的愛好書是存儲我插入一個名字的每一個愛好。有人可以幫我修理它嗎?如何將一組多個值添加到一個鍵?

class Hobby: 

    def __init__(self): 
     self.dic={} 
     self.hby=set() 

    def enter(self,n,h): 

     if n not in self.dic.items(): 
      self.dic[n]=self.hby 
       for k in self.dic.items(): 
        self.hby.add(h) 

    def lookup(self,n): 
     return self.dic[n] 

我試圖運行下列情形

d = Hobby(); d.enter('Roj', 'soccer'); d.lookup('Roj') 
    {'soccer'} 
    d.enter('Max', 'reading'); d.lookup('Max') 
    {'reading', 'soccer'} #should return just reading 
    d.enter('Roj', 'music'); d.lookup('Roj') 
    {'reading', 'soccer','music'} #should return soccer and music 

回答

2

你爲什麼要重新發明這裏dict?爲什麼你要使用一個單獨的集合,並且總是爲其添加值,並將其引用到每個確保它總是在查找時返回相同集合的鍵?

不要重新發明輪子,用collections.defaultdict

import collections 

d = collections.defaultdict(set) 
d["Roj"].add("soccer") 
d["Roj"] 
# {'soccer'} 
d["Max"].add("reading") 
d["Max"] 
# {'reading'} 
d["Roj"].add("music") 
d["Roj"] 
# {'soccer', 'music'} 

UPDATE - 如果你真的想這樣做,通過自己的類(和之前你做什麼,看Stop Writing Classes!),你可以做到這一點是:

class Hobby(object): 

    def __init__(self): 
     self.container = {} 

    def enter(self, n, h): 
     if n not in self.container: 
      self.container[n] = {h} 
     else: 
      self.container[n].add(h) 

    def lookup(self, n): 
     return self.container.get(n, None) 

d = Hobby() 
d.enter("Roj", "soccer") 
d.lookup("Roj") 
# {'soccer'} 
d.enter("Max", "reading") 
d.lookup("Max") 
# {'reading'} 
d.enter("Roj", "music") 
d.lookup("Roj") 
# {'soccer', 'music'} 

注意沒有額外的設置是如何使用在這裏 - 每個dict密鑰都有自己的set來填充。

相關問題