让我在 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。频率 + word1.频率 - 否则将
word1添加到集合中
我该怎么做?
之前我使用列表来检查列表是否包含一个 Word 对象,该对象具有与 word1.lemma 相同的 lemma .但是该方法在集合中添加 n 个 word 的复杂度为 O(n^2)。
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
请您参考如下方法:
你可以通过使用字典而不是列表来轻松地做到这一点,使用 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
