鱼C论坛

 找回密码
 立即注册
查看: 1316|回复: 5

0基础学python13课课后练习问题

[复制链接]
发表于 2018-4-11 16:43:02 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
第七题,关于生成器,我敲了代码进去,显示tuple1的type为generator,但无论是next()还是_next_()均说generator object has no attribute.咋回事儿涅?我用的是3.7版本。谢谢老师们!
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2018-4-11 16:53:15 | 显示全部楼层
把代码贴出来
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-4-11 16:56:12 | 显示全部楼层
  1. def myRange(n):
  2.     i = 0
  3.     while i < n:
  4.         yield i
  5.         i += 1

  6. a = myRange(10)
  7. for i in range(10):
  8.     print(next(a))
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-4-11 17:05:41 | 显示全部楼层
最后的for循环改为
  1. for i in a:
  2.     print(i)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-4-11 20:49:51 | 显示全部楼层
  1. tuple1=(x**2 for x in range(10))
复制代码
  1. >>> type(tuple1)
  2. <class 'generator'>
复制代码

上面没问题,下面系统说generator object has no attribute ’__next__‘.
  1. >>> tuple1.__next__()
  2. 0
  3. >>> tuple1.__next__()
  4. 1
  5. >>> tuple1.__next__()
  6. 4
  7. >>> tuple1.__next__()
  8. 9
  9. >>> tuple1.__next__()
  10. 16
  11. >>> tuple1.__next__()
  12. 25
  13. >>> tuple1.__next__()
  14. 36
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-4-27 02:08:12 | 显示全部楼层
Python魔术方法__next__() => next()函数
==========================
>>> g = (x**2 for x in range(1, 6))
>>> next(g)
1
>>> next(g)
4
>>> next(g)
9
>>> next(g)
16
>>> next(g)
25
>>> next(g)
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    next(g)
StopIteration

生成器是一次性消费,用完就没了。

我们可以实现自己的生成器函数,使用yield关键字

>>> def gen():
        yield 1

>>> next(a)
1
>>> next(a)
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    next(a)
StopIteration

因为没有while循环作为外层保护,这里gen在生产了1后就壮烈的死掉了。

更一般的是迭代器,任何实现了【迭代协议】的类都是迭代器,迭代器的next函数返回自身迭代对象

>>> class It(object):
        def __init__(self):
                self.a = 1
                self.b = 1
        def __iter__(self):
                return self
        def __next__(self):
                self.a, self.b = self.a+self.b, self.a
                return self.a

       
>>> d = It()
>>> next(d)
2
>>> next(d)
3
>>> next(d)
5
>>> next(d)
8
>>> next(d)
13
>>>

生成器可以看成是迭代器的特殊情况
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-12-29 07:29

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表