Python报错

一、关于缩进问题报错

>>> import trees
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    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 "<pyshell#4>", line 1, in <module>
    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 "<pyshell#5>", line 1, in <module>
    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 "<pyshell#9>", line 1, in <module>
    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'





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值