【问题标题】:How to add a set of multiple values to a key?如何将一组多个值添加到键?
【发布时间】:2017-06-07 01:29:47
【问题描述】:

我创建了一个基本上是一本爱好书的课程。可以通过两种方法访问这本书,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

【问题讨论】:

    标签: python-3.x class dictionary set


    【解决方案1】:

    你为什么要在这里重新发明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'}
    

    .

    更新 - 如果你真的想通过自己的课程来完成(在你这样做之前,请观看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 来填充。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-11
      • 2015-02-16
      • 2019-05-30
      • 2021-04-05
      相关资源
      最近更新 更多