迭代器和生成器

迭代器和生成器

迭代器

迭代

可迭代對象

hasattr(list,'iter')
True

判斷列表是否為可迭代對象


迭代器

lst = [1,2,3]
hasattr(lst,'next')
False ——列表不是迭代器
iter_lst = iter(lst) ——?jiǎng)?chuàng)建迭代器
iter_lst
<list_iterator object at 0x00000123E17DE820>
iter_lst.next()
1
iter_lst.next()
2
iter_lst.next()
3
iter_lst.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

迭代器執(zhí)行過程

for循環(huán)

import dis
dis.dis('for i in lst:pass')
1 0 LOAD_NAME 0 (lst)
2 GET_ITER
4 FOR_ITER 4 (to 10)
6 STORE_NAME 1 (i)
8 JUMP_ABSOLUTE 4
10 LOAD_CONST 0 (None)
12 RETURN_VALUE

另一種生成迭代器對象的方式

import itertools
c = itertools.count(start = 3)
dir(c)
['class', 'delattr', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'iter', 'le', 'lt', 'ne', 'new', 'next', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook']
next(c)
3
next(c)
4
colors = itertools.cycle(['red', 'green', 'blue']) —— 可循環(huán)迭代器對象
next(colors)
'red'
next(colors)
'green'
next(colors)
'blue'
next(colors)
'red'

生成器

  • 類似普通函數(shù),不同點(diǎn)在于其包含yield表達(dá)式
  • 生成器也是迭代器

def g():
... yield 0
... yield 1
... yield 2
...
ge = g()
dir(ge)
['class', 'del', 'delattr', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'iter', 'le', 'lt', 'name', 'ne', 'new', 'next', 'qualname', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'close', 'gi_code', 'gi_frame', 'gi_running', 'gi_yieldfrom', 'send', 'throw']
ge
<generator object g at 0x00000123E34B7F20>
ge.next()
0
ge.next()
1
ge.next()
2
ge.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

def y_yield(n): ————定義生成器對象函數(shù)
... while n>0:
... print('before yield')
... yield n
... n -= 1
... print('after yield')
...
yy = y_yield(3)
yy.next()
before yield
3
yy.next()
after yield
before yield
2
yy.next()
after yield
before yield
1
yy.next()
after yield
next(c)
3
>>> next(c)
4
>>> colors = itertools.cycle(['red', 'green', 'blue']) —— 可循環(huán)迭代器對象
>>> next(colors)
'red'
>>> next(colors)
'green'
>>> next(colors)
'blue'
>>> next(colors)
'red'

##生成器
- 類似普通函數(shù),不同點(diǎn)在于其包含yield表達(dá)式
- 生成器也是迭代器

>>> def g():
... yield 0
... yield 1
... yield 2
...
>>> ge = g()
>>> dir(ge)
['class', 'del', 'delattr', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'iter', 'le', 'lt', 'name', 'ne', 'new', 'next', 'qualname', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'close', 'gi_code', 'gi_frame', 'gi_running', 'gi_yieldfrom', 'send', 'throw']
>>> ge
<generator object g at 0x00000123E34B7F20>
>>> ge.next()
0
>>> ge.next()
1
>>> ge.next()
2
>>> ge.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

>>> def y_yield(n): ————定義生成器對象函數(shù)
... while n>0:
... print('before yield')
... yield n
... n -= 1
... print('after yield')
...
>>> yy = y_yield(3)
>>> yy.next()
before yield
3
>>> yy.next()
after yield
before yield
2
>>> yy.next()
after yield
before yield
1
>>> yy.next()
after yield
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

生成器解析
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 迭代器協(xié)議 1.迭代器協(xié)議是指:對象必須提供一個(gè)next方法,執(zhí)行該方法要么返回迭代中的下一項(xiàng),要么就引起一個(gè)St...
    貓茂懋閱讀 657評論 1 2
  • 迭代器模式:一種惰性獲取數(shù)據(jù)項(xiàng)的方式,即按需一次獲取一個(gè)數(shù)據(jù)項(xiàng)。 關(guān)于迭代器和生成器的區(qū)別:在Python社區(qū)中,...
    Zoulf閱讀 1,259評論 0 1
  • 我的人生處處是意外。從未想過做老師,卻意外地站上了三尺講臺(tái);從未想過當(dāng)班主任,卻意外的在班主任這條路上一走...
    輕言清語閱讀 329評論 0 7
  • 猛地一驚五月已過,今天是六月,好快,感覺才開啟簡書第一篇文章就是四月的總結(jié),現(xiàn)在五月也已經(jīng)逝去~ 六一兒童節(jié)屬于孩...
    云卷云舒H閱讀 129評論 0 1
  • 這本書講述的是一群屬于動(dòng)物們造反后的烏托邦幻想破滅的故事。農(nóng)場的動(dòng)物們自以為趕跑了農(nóng)場主,他們就可以做自己的主人,...
    倚歌漫醉閱讀 262評論 0 0

友情鏈接更多精彩內(nèi)容