让我在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
添加到集合我该怎么办?
以前,我使用列表来检查列表中是否包含Word
与lemma
相同的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
答案 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中的数据结构。
如果您确实需要Word
和Corpus
两个类,则应继续使用以下代码:
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
关键点是:
dict
查找(例如'b' in {'a': 23, 'b': 24}
)-When does __eq__ gets called using hash()? defaultdict
的用法__eq__
和__hash__
的使用情况我强烈建议您考虑是否真的要在Word
中存储Corpus
实例。