如何在Python中从用户定义的类创建集合

时间:2019-03-13 15:45:20

标签: python list dictionary collections

让我在python中拥有以下课程:

class Word:
def __init__(self, _lemma, _frequency):
    self.lemma = str(_lemma)
    self.frequency = int(_frequency) 

现在我想创建一个类Word的集合,当将Word对象word1添加到集合时,该集合具有以下逻辑:

  • 如果集合包含Word对象word,其中word.lemma = word1.lemma,则word.frequency = word.frequency + word1.frequency
  • word1添加到集合

我该怎么办?


以前,我使用列表来检查列表中是否包含Wordlemma相同的word1.lemma对象。但是该方法具有O(n ^ 2)的复杂度,无法在集合中添加n word

from Word import Word

class Corpus:

    def __init__(self, _name, _total_count):
        self.name = str(_name)
        self.total_count = int(_total_count)
        self.words = []

    def add(self, _word):

        find_word = [index for index, word in enumerate(self.words) if word.lemma == _word.lemma]  # O(n)
        if len(find_word) == 0:
            self.words.append(Word(_word.lemma, _word.frequency))
        else:
            self.words[find_word[0]].frequency = self.words[find_word[0]].frequency + _word.frequency

2 个答案:

答案 0 :(得分:3)

使用word.lemma作为关键字,您可以通过使用字典而不是列表来轻松完成此操作:

def add(self, _word):
    if _word.lemma not in self.words:
        self.words[_word.lemma] = _word
    else:
        self.words[_word.lemma].frequency += _word.frequency

一个不便之处是它复制了引理信息...


如果不是必须使用Word类,则可以使用defaultdict(默认值为0),该频率仅将频率(值)与引理(关键字)相关联:

class Corpus:
    def __init__(...):
        ...
        self.words = defaultdict(lambda: 0)

    def add(self, lemma, frequency):
        self.words[lemma] += frequency

答案 1 :(得分:2)

您的措辞可能会使熟悉Python的社区成员感到困惑。我认为您将“字典”一词用作域模型的一部分,而不是Python中的数据结构。

如果您确实需要WordCorpus两个类,则应继续使用以下代码:

from collections import defaultdict


class Word:

    def __init__(self, lemma: str, frequency: int):
        self.lemma = lemma
        self.frequency = frequency

    def __eq__(self, other):
        return self.lemma == other.lemma

   def __hash__(self):
       return hash(self.lemma)


class Corpus:

    def __init__(self):
        self.words = defaultdict(0)

    def add(self, word: Word):
        self.words[word] += word.frequency

关键点是:

  1. type hints
  2. 的用法
  3. 如何进行dict查找(例如'b' in {'a': 23, 'b': 24})-When does __eq__ gets called using hash()?
  4. defaultdict的用法
  5. __eq____hash__的使用情况

我强烈建议您考虑是否真的要在Word中存储Corpus实例。

相关问题