首页 > 编程 > Python > 正文

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

2019-11-25 16:15:55
字体:
来源:转载
供稿:网友

本文实例讲述了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= 1g= 1g= 2g= 3g= 5g= 8Generrator return value: done

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python数据结构与算法教程》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表