简体   繁体   English

在 Python 中赋值之前可能会引用局部变量

[英]local variable might be referenced before assignment in Python

I'm going through some code that implements a decision tree learner.我正在研究一些实现决策树学习器的代码。 Here is the code:这是代码:

def calculate_entropy(self, tags):

    tags_counter = Counter()

    if len(tags) > 0:
        for tag in tags:
            tags_counter[tag] += 1
            classes_probs = [float(tags_counter[tag]) / len(tags) for tag in tags_counter]

        entropy = 0
        for prob in classes_probs:
            if prob == 0:
                return 0
            entropy -= prob * math.log(prob, 2)

        return entropy

    else:
        return 0

My questions are:我的问题是:

  1. for classes_probs I get a local variable might be referenced before assignment message, and I can't figure why.对于 classes_probs 我得到一个局部变量可能在赋值消息之前被引用,我不知道为什么。
  2. what does the code on the right side of the placement into classes probs do?放置到类 probs 右侧的代码有什么作用? I haven't seen anything like it.我没见过类似的东西。

(1) The warning is because classes_probs may be undefined at that point. (1) 警告是因为classes_probs在这一点上可能未定义。 If tags is empty, the first loop doesn't execute.如果tags为空,第一个循环不执行。 You can "fix" this by assigning an empty list before the first loop.您可以通过在第一个循环之前分配一个空列表来“修复”这个问题。

(2) This is called a list comprehension . (2) 这称为list comprehension Use that search term and find a tutorial at your preferred level of writing and examples.使用该搜索词并找到您喜欢的写作和示例级别的教程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在赋值之前可能会引用局部变量 - Python - Local variable might be referenced before assignment - Python 局部变量可能在赋值前被引用 - Local Variable might ne referenced before assignment 局部变量“result”可能在赋值前被引用 - Local variable 'result' might be referenced before assignment 局部变量“put”可能在赋值之前被引用 - Local variable 'put' might be referenced before assignment 分配前可能会引用局部变量 - Local variable might be referenced before assignment Python错误,分配前可能会引用局部变量,if条件之外的变量 - Python Error, Local variable might be referenced before assignment, variable outside the if condition 强制 While 循环使局部变量可能在赋值前被引用 - Mandatory While Loop Gives Local Variable Might Be Referenced Before Assignment Pycharm - 禁用'局部变量'xxx'可能在赋值之前被引用' - Pycharm - Disable 'Local variable 'xxx' might be referenced before assignment' 错误“分配前可能会引用局部变量‘结果’” - Error "Local variable 'results' might be referenced before assignment" Pylint 没有捕捉到“局部变量 'xyz' 可能在赋值之前被引用”但 PyCharm 使用 python 2.7 突出显示相同 - Pylint is not catching "Local variable 'xyz' might be referenced before assignment " but PyCharm is highlighing the same, using python 2.7
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM