local variable might be referenced before assignment in Python

时间:2019-01-15 18:15:54

标签: 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.
  2. what does the code on the right side of the placement into classes probs do? I haven't seen anything like it.

1 个答案:

答案 0 :(得分:0)

(1) The warning is because classes_probs may be undefined at that point. If tags is empty, the first loop doesn't execute. You can "fix" this by assigning an empty list before the first loop.

(2) This is called a list comprehension. Use that search term and find a tutorial at your preferred level of writing and examples.