Skip to main content
 首页 » 编程设计

python之更新 numpy 数组中的值时修复代码重复

2025年02月15日7unruledboy

我的 python 代码中有以下函数:

def mk_standard_vectors(self, know): 
 
    vector_type = 'k' if know else 'h' 
    for name,se in self.sparse_entities.items(): 
      if name[-1] == vector_type: 
        word = se.word 
        for feature in (feature for c in se.contexts for feature in c.dlfs): 
          self.vector_space.vectors[word][self.vector_space.contexts_to_id[feature]]+=1 
          self.vector_space.vectors[feature][self.vector_space.contexts_to_id[word]]+=1 

Codeclimate 提示此函数中的代码重复。具体来说,关于两行阅读:

self.vector_space.vectors[word][self.vector_space.contexts_to_id[feature]]+=1 
self.vector_space.vectors[feature][self.vector_space.contexts_to_id[word]]+=1 

这两行更新了 numpy 数组中的特定值。基本上,我有一个 vector_space 类和一个 vectors 字典,它按单词值索引 numpy 数组。当我运行上面的函数时,对于任何对(单词,特征),我都会更新由 word 索引的数组中与 feature 对应的位置,然后相反。有没有什么巧妙的方法来压缩代码并满足codeclimate?

(当然,我可以写一个额外的函数,但我看不出它会让事情变得特别干净或更有效率。除非我遗漏了什么......)

请您参考如下方法:

在这种情况下,我会保持原样。很清楚你在那里做什么。有时应该忽略此类准则 - 并非总是如此,但如果有正当理由打破它们,你应该被允许打破它们。

但如果你真的想避免警告,你可以将其包装为“子迭代”:

# ... 
for feature in (feature for c in se.contexts for feature in c.dlfs): 
    for vec, context in ((word, feature), (feature, word)): 
        self.vector_space.vectors[vec][self.vector_space.contexts_to_id[context]] += 1