我想跟踪计算余弦相似度分数的当前最大值。然而,我一直得到错误UnboundLocalError: cannot access local variable 'current_max_cosine_similarity_score' where it is not associated with a value
在Javascript中,当处理函数作用域之外的变量时,我通常可以使用let
关键字来做到这一点,而不会出现问题。然而,在Python中似乎不是这样。
python应该怎么做呢?
current_max_cosine_similarity_score = -math.inf
def func(acc, v):
calculated_cosine_similarity_score = ...
if calculated_cosine_similarity_score > current_max_cosine_similarity_score:
current_max_cosine_similarity_score = max([current_max_cosine_similarity_score, calculated_cosine_similarity_score])
acc['cosineSimilarityScore'] = calculated_cosine_similarity_score
return acc
print(reduce(func, [...], {}))
必须在func()
中将current_max_cosine_similarity_score
声明为global
(或nonlocal
)。但这仍然是个坏主意。"pythonic"方法是使用生成器、闭包或带有get_current_maximum()
的类。
可能是最"pythonic">解决您的问题:
from functools import reduce
def calc_closure():
def _calc(value, element):
# do calculations on element here
if element > value:
_calc.current_max_value = element
return _calc.current_max_value
# using an attribute makes current_max_value accessible from outer
_calc.current_max_value = -np.math.inf
return _calc
closure_1 = calc_closure()
closure_2 = calc_closure()
print(reduce(closure_1, [1, 2, 3, 4, 1]))
print(closure_1.current_max_value )
print(closure_2.current_max_value )
输出:
4
从