Python报错
来源:互联网 发布:汉维智能高清网络 编辑:程序博客网 时间:2024/05/05 07:35
一、关于缩进问题报错
>>> import treesTraceback (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 treesTraceback (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 treesTraceback (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
- python sqlite3 报错
- 配置文件Python报错
- Python报错
- python 报错
- python 报错
- Python安装报错
- python报错
- python virtualenv报错!
- python报错MemoryError
- Linux_yum / Python 报错
- python 报错集合
- python 报错笔记
- python 报错函数
- python 报错记录
- python 报错解决办法
- python运行报错
- python urllib2 urlopen 报BadStatusLine 报错
- python连接mysql报错
- 幻读和不可重复读的区别
- Struts国际化解读
- C++中vector内存泄露问题
- struts2 标签库中的%和#的区别
- poj 1631 Bridging signals
- Python报错
- 事务隔离级别
- HtmlUnit的使用
- Activiti 流程启动及节点流转源码分析
- offset、offsetLeft,offsetWidth和offsetHeight的使用方法
- Android4.4 增加屏幕旋转功能
- scatter_matrix&df.plot&sns.boxplot
- 技术网站
- Angular vs React – so which do I chose?