Python报错

一、关于缩进问题报错

>>> import trees
Traceback (most recent call last):
  File "", line 1, in 
    import trees
  File "D:\Python\trees.py", line 9
    labelCounts[currentLabel] = 0
                                ^
TabError: inconsistent use of tabs and spaces in indentation
>>> import trees
Traceback (most recent call last):
  File "", line 1, in 
    import trees
  File "D:\Python\trees.py", line 9
    labelCounts[currentLabel] = 0
              ^
IndentationError: expected an indented block
>>> import trees
Traceback (most recent call last):
  File "", line 1, in 
    import trees
  File "D:\Python\trees.py", line 11
    shannonEnt = 0.0
                   ^
IndentationError: unindent does not match any outer indentation level
以上三种都是有关缩进问题的报错,第二段代码是由于没有缩进导致报错,;第一段和第三段是由于空格和tab混用……

所以要注意缩进问题,空格和tab不能混用。

二、“dict_keys”对象不支持索引

例子来源于《机器学习实战》决策树

def classify(inputTree, featLabels, testVec):
    firstStr = inputTree.keys()[0]                      #line 78
    secondDict = inputTree[firstStr]
    featIndex = featLabels.index(firstStr)
    for key in secondDict.keys():
        if testVec[featIndex] == key:
            if type(secondDict[key]).__name__ == 'dict':
                classLabel = classify(secondDict[key], featLabels, testVec)
            else:
                classLabel = secondDict[key]
    return classLabel
如果使用上面的决策树分类函数,报错:

>>> trees.classify(myTree, labels, [1,0])
Traceback (most recent call last):
  File "", line 1, in 
    trees.classify(myTree, labels, [1,0])
  File "D:\Python\trees.py", line 78, in classify
    firstStr = inputTree.keys()[0]
TypeError: 'dict_keys' object does not support indexing
这是因为Python2.x与3.x的差别导致的。这时我们可以用list(inputTree.keys())或者list(inputTree)来解决。

详细代码如下:

def classify(inputTree, featLabels, testVec):
    firstStr = list(inputTree.keys())[0]
    secondDict = inputTree[firstStr]
    featIndex = featLabels.index(firstStr)
    for key in secondDict.keys():
        if testVec[featIndex] == key:
            if type(secondDict[key]).__name__ == 'dict':
                classLabel = classify(secondDict[key], featLabels, testVec)
            else:
                classLabel = secondDict[key]
    return classLabel
>>> trees.classify(myTree, labels, [1,0])
'no'





你可能感兴趣的:(学习,python)