Python使用迭代器捕获Generator返回值的方法


Posted in Python onApril 05, 2017

本文实例讲述了Python使用迭代器捕获Generator返回值的方法。分享给大家供大家参考,具体如下:

用for循环调用generator时,发现拿不到generator的return语句的返回值。如果想要拿到返回值,必须捕获StopIteration错误,返回值包含在StopIteration的value中:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
def fib(max):
  n, a, b = 0, 0, 1
  while n < max:
    yield b
    a, b = b, a + b
    n = n + 1
  return 'done'
# 捕获Generator的返回值
g = fib(6)
while True:
  try:
    x=next(g)
    print('g=',x)
  except StopIteration as e:
    print('Generrator return value:', e.value)
    break

输出:

g= 1
g= 1
g= 2
g= 3
g= 5
g= 8
Generrator return value: done

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
Python continue语句用法实例
Mar 11 Python
用pickle存储Python的原生对象方法
Apr 28 Python
用python做一个搜索引擎(Pylucene)的实例代码
Jul 05 Python
Python之多线程爬虫抓取网页图片的示例代码
Jan 10 Python
python绘制立方体的方法
Jul 02 Python
python实践项目之监控当前联网状态详情
May 23 Python
Django 接收Post请求数据,并保存到数据库的实现方法
Jul 12 Python
解决pytorch GPU 计算过程中出现内存耗尽的问题
Aug 19 Python
使用 Python 遍历目录树的方法
Feb 29 Python
jupyter 使用Pillow包显示图像时inline显示方式
Apr 24 Python
关于 Python json中load和loads区别
Nov 07 Python
python机器学习Github已达8.9Kstars模型解释器LIME
Nov 23 Python
由浅入深讲解python中的yield与generator
Apr 05 #Python
Python中shutil模块的学习笔记教程
Apr 04 #Python
python 遍历字符串(含汉字)实例详解
Apr 04 #Python
python模拟登录并且保持cookie的方法详解
Apr 04 #Python
python 容器总结整理
Apr 04 #Python
详解Python中最难理解的点-装饰器
Apr 03 #Python
JSON Web Tokens的实现原理
Apr 02 #Python
You might like
54个提高PHP程序运行效率的方法
2015/07/19 PHP
在WordPress中使用PHP脚本来判断访客来自什么国家
2015/12/10 PHP
php实现的生成迷宫与迷宫寻址算法完整实例
2017/11/06 PHP
php unlink()函数使用教程
2018/07/12 PHP
javascript抖动元素的小例子
2013/10/28 Javascript
JQuery Highcharts 动态生成图表的方法
2013/11/15 Javascript
js截取固定长度的中英文字符的简单实例
2013/11/22 Javascript
jQuery学习笔记之jQuery.fn.init()的参数分析
2014/06/09 Javascript
javascript实现根据iphone屏幕方向调用不同样式表的方法
2015/07/13 Javascript
jQuery实现将div中滚动条滚动到指定位置的方法
2016/08/10 Javascript
利用node.js写一个爬取知乎妹纸图的小爬虫
2017/05/03 Javascript
nodejs开发微信小程序实现密码加密
2017/07/11 NodeJs
vue+element-ui实现表格编辑的三种实现方式
2018/10/31 Javascript
js图片无缝滚动插件使用详解
2020/05/26 Javascript
[44:39]2014 DOTA2国际邀请赛中国区预选赛 NE VS CNB
2014/05/21 DOTA
[03:36]2015国际邀请赛第二日现场精彩集锦
2015/08/06 DOTA
[01:11:08]Winstrike vs NB 2018国际邀请赛淘汰赛BO1 8.21
2018/08/22 DOTA
python打开网页和暂停实例
2014/09/30 Python
python打开文件并获取文件相关属性的方法
2015/04/23 Python
Python爬虫设置代理IP的方法(爬虫技巧)
2018/03/04 Python
python字符串与url编码的转换实例
2018/05/10 Python
django用户登录和注销的实现方法
2018/07/16 Python
python安装scipy的方法步骤
2019/06/26 Python
Python 使用 docopt 解析json参数文件过程讲解
2019/08/13 Python
python实现while循环打印星星的四种形状
2019/11/23 Python
python中count函数简单用法
2020/01/05 Python
pandas读取csv文件提示不存在的解决方法及原因分析
2020/04/21 Python
英国口碑最好的的维他命胶囊品牌:Myvitamins(有中文站)
2016/12/03 全球购物
和睦家庭事迹
2014/05/14 职场文书
体育专业自荐书
2014/05/29 职场文书
医院标语大全
2014/06/23 职场文书
写给老婆的保证书
2015/02/27 职场文书
行政上诉状范文
2015/05/23 职场文书
春晚观后感
2015/06/11 职场文书
Django使用redis配置缓存的方法
2021/06/01 Redis
Python多线程 Queue 模块常见用法
2021/07/04 Python