gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:28:10 25 4
gpt4 key购买 nike

让我在 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

关于python - 如何在 Python 中从用户定义的类创建集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55145942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com