python 3.2 错误 ‘generator’ object has no attribute ‘next’
2016-06-24 10:08
671 查看
下面是一段简单的示例
#定义Generator函数
def func(n):
for i in range(n):
yield i
#在for循环中输出
for i in func(3):
print(i)
#使用next()输出
r = func(4)
print(r.next())
运行结果:
0
1
2
Traceback (most recent call last):
File "C:\Users\BEM\Desktop\test.py", line 10, in <module>
print(r.next())
AttributeError: 'generator' object has no attribute 'next'
出错的原因是因为:
原因是在Python3.2中 generator(有yield关键字的函数则会被识别为generator函数)中的next变为__next__了,next是以前版本中的方法
修改为下面这样运行正常
将
print(r.next())
代码修改为
print(next(r))
就可以成功运行
因为只是测试了Python3.2中next()的方法,应该Python 3.x都是采用上述方法
附加提示:当在使用next(r)函数前使用list(r)时会出现以下错误:
Traceback (most recent call last):
File "C:\Users\BEM\Desktop\test.py", line 12, in <module>
print(next(r))
StopIteration
因为list()函数已经把数据以列表的形式生成,当使用next()时已经没有数据可生成了
#定义Generator函数
def func(n):
for i in range(n):
yield i
#在for循环中输出
for i in func(3):
print(i)
#使用next()输出
r = func(4)
print(r.next())
运行结果:
0
1
2
Traceback (most recent call last):
File "C:\Users\BEM\Desktop\test.py", line 10, in <module>
print(r.next())
AttributeError: 'generator' object has no attribute 'next'
出错的原因是因为:
原因是在Python3.2中 generator(有yield关键字的函数则会被识别为generator函数)中的next变为__next__了,next是以前版本中的方法
修改为下面这样运行正常
将
print(r.next())
代码修改为
print(next(r))
就可以成功运行
因为只是测试了Python3.2中next()的方法,应该Python 3.x都是采用上述方法
附加提示:当在使用next(r)函数前使用list(r)时会出现以下错误:
Traceback (most recent call last):
File "C:\Users\BEM\Desktop\test.py", line 12, in <module>
print(next(r))
StopIteration
因为list()函数已经把数据以列表的形式生成,当使用next()时已经没有数据可生成了
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法