让我在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
与. 但是该方法在集合中添加 n 具有 O(n^2) 复杂性。lemma
word1.lemma
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